4

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

4

1 回答 1

2

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();
 }

例如:https ://fernando.requeixo.com/addNodefromHTML.php

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

于 2017-10-17T01:40:58.790 回答