note 91513 added to domdocument.loadhtml

From: Date: Sun, 14 Jun 2009 15:29:19 +0000
Subject: note 91513 added to domdocument.loadhtml
Groups: php.notes 
Request: Send a blank email to php-notes+get-156856@lists.php.net to get a copy of this message
Here is a function I wrote to capitalize the previous remarks about charset problems (UTF-8...) when using loadHTML 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.loadhtml.php Edit -- https://master.php.net/note/edit/91513 Del: integrated -- https://master.php.net/note/delete/91513/integrated Del: useless -- https://master.php.net/note/delete/91513/useless Del: bad code -- https://master.php.net/note/delete/91513/bad+code Del: spam -- https://master.php.net/note/delete/91513/spam Del: non-english -- https://master.php.net/note/delete/91513/non-english Del: in docs -- https://master.php.net/note/delete/91513/in+docs Del: other reasons-- https://master.php.net/note/delete/91513 Reject -- https://master.php.net/note/reject/91513 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#156856) next »