note 91515 added to domdocument.loadhtmlfile

From: Date: Sun, 14 Jun 2009 15:35:38 +0000
Subject: note 91515 added to domdocument.loadhtmlfile
Groups: php.notes 
Request: Send a blank email to php-notes+get-156858@lists.php.net to get a copy of this message
Here is a function I wrote to capitalize on the previous remarks about charset problems (UTF-8...) when using loadHTML/loadHTMLFile and then DOM functions. It adds the charset meta tag just after <head> to improve automatic encoding detection, converts any specific character to an html entity, thus PHP DOM functions/attributes will return correct values. <?php mb_detect_order("ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15"); function loadNprepare($url,$encod='') { $content = file_get_contents($url); if (!empty($content)) { if (empty($encod)) $encod = mb_detect_encoding($content); $headpos = mb_strpos($content,'<head>'); if (FALSE=== $headpos) $headpos= mb_strpos($content,'<HEAD>'); if (FALSE!== $headpos) { $headpos+=6; $content = mb_substr($content,0,$headpos) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr($content,$headpos); } $content=mb_convert_encoding($content, 'HTML-ENTITIES', $encod); } $dom = new DomDocument; $res = $dom->loadHTML($content); if (!$res) return FALSE; return $dom; } ?> NB: it uses mb_strpos/mb_substr instead of mb_ereg_replace because that seemed more efficient with huge html pages. ---- Server IP: 64.71.164.2 Probable Submitter: 80.236.100.242 ---- Manual Page -- http://www.php.net/manual/en/domdocument.loadhtmlfile.php Edit -- https://master.php.net/note/edit/91515 Del: integrated -- https://master.php.net/note/delete/91515/integrated Del: useless -- https://master.php.net/note/delete/91515/useless Del: bad code -- https://master.php.net/note/delete/91515/bad+code Del: spam -- https://master.php.net/note/delete/91515/spam Del: non-english -- https://master.php.net/note/delete/91515/non-english Del: in docs -- https://master.php.net/note/delete/91515/in+docs Del: other reasons-- https://master.php.net/note/delete/91515 Reject -- https://master.php.net/note/reject/91515 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#156858) next »