gpt4 book ai didi

php - 从 HTML 片段的字符串创建 DOMNode

转载 作者:搜寻专家 更新时间:2023-10-31 21:37:55 27 4
gpt4 key购买 nike

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

最佳答案

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 添加到源的选定节点)

关于php - 从 HTML 片段的字符串创建 DOMNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14839879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com