从HTML片段的字符串创建DOMNode

时间:2013-02-12 19:04:53

标签: php dom

如何从HTML片段的字符串创建DOMNode,当然假设字符串包含单个根节点?

1 个答案:

答案 0 :(得分:1)

DOMDocumentFragments 确实有 loadXML()方法

libxml_use_internal_errors(1);

$opts = array('http' => array('header' => 'Accept-Charset: ISO-8859-1, *;q=0'));
$context = stream_context_create($opts);
$html = file_get_contents( 'http://multiple.webcindario.com/wstest.php' , false , $context );

$html = html_entity_decode(htmlentities($html, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-1');
ob_clean();
$classname = "product";
$domdocument = new DOMDocument();
$domdocument->preserveWhiteSpace = true;
$domdocument->formatOutput       = false;
$domdocument->loadHTML($html);
$xpath = new DOMXPath($domdocument);
$found = $xpath->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

$newHTML="<div class='foo bar'><p>This is <b>an <i>example</i></b> paragraph    <a href='#!'>#!</a></p></div>";
$newHTML = html_entity_decode(htmlentities($newHTML, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-1');

foreach($found as $oldnode){
   $frag = $domdocument->createDocumentFragment();
   $frag->appendXML($newHTML);
   $oldnode->appendChild($frag);
   $updatedHTML=$domdocument->saveHTML();
 }

ex:http://multiple.webcindario.com/addNodefromHTML.php

(这会将一个示例段落作为chilNode添加到源的选定节点)