从HTML片段的字符串创建DOMNode [英] Create a DOMNode from a string of an HTML fragment

查看:60
本文介绍了从HTML片段的字符串创建DOMNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I create a DOMNode from a string of an HTML fragment, assuming of course the string contains a single root node?

推荐答案

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

例如: http://multiple.webcindario.com/addNodefromHTML.php

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

(this adds an example paragraph as a chilNode to the selected Nodes of the source)

这篇关于从HTML片段的字符串创建DOMNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆