我需要使用 PHP 按 ID 搜索元素,然后向其附加 html 内容。这看起来很简单,但我是 php 新手,找不到合适的函数来执行此操作。
$html = file_get_contents('http://example.com');
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
$descBox = $doc->getElementById('element1');
我只是不知道下一步该怎么做。任何帮助,将不胜感激。
就像克里斯在评论中提到的那样尝试使用DOMNode::appendChild,这将允许您向所选元素添加子元素并且DOMDocument::createElement像这样实际创建元素:
$html = file_get_contents('http://example.com');
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($html);
//get the element you want to append to
$descBox = $doc->getElementById('element1');
//create the element to append to #element1
$appended = $doc->createElement('div', 'This is a test element.');
//actually append the element
$descBox->appendChild($appended);
或者,如果您已经有要附加的 HTML 字符串,您可以创建文档片段像这样:
$html = file_get_contents('http://example.com');
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($html);
//get the element you want to append to
$descBox = $doc->getElementById('element1');
//create the fragment
$fragment = $doc->createDocumentFragment();
//add content to fragment
$fragment->appendXML('<div>This is a test element.</div>');
//actually append the element
$descBox->appendChild($fragment);
请注意,任何使用 JavaScript 添加的元素都将无法被 PHP 访问。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)