使用php DOM和xpath为特定注释提供属性的整个parentNode?
我想输出带有属性(ID或类)的注释的parentNode 如果我有这个html代码使用php DOM和xpath为特定注释提供属性的整个parentNode?,php,xpath,domdocument,Php,Xpath,Domdocument,我想输出带有属性(ID或类)的注释的parentNode 如果我有这个html代码 <div><span><!--test--></span><div class="myclass"><!--test_comment--></div></div> <div><span id="myid" style="color:blue;font-weight:bold"><!--t
<div><span><!--test--></span><div class="myclass"><!--test_comment--></div></div>
<div><span id="myid" style="color:blue;font-weight:bold"><!--test_comment--></span><div class="myclass"><!--test--></div></div>
如何获取div中的属性(类或ID)?nodeValue不工作
当我还是新手时,也欢迎对我的代码发表任何其他评论
<?php
$dom = new DOMDocument;
$dom->loadHTML(data());
$xpath = new DOMXPath($dom);
$node = $xpath->query('//*[comment()]');
foreach( $node as $p ) {
echo 'output: ', $dom->saveXML($p), "\r\n";
}
function data() {
return <<< STR
<div><span id="myid" style="color:blue;font-weight:bold"><!--test--></span><p>no comment here</p><div class="myclass"><!--test_comment--></div></div>
STR;
}
<span id="myid" style="color:blue;font-weight:bold"><!--test_comment--></span>
<?php
$html = <<<STR
<div><span><!--test--></span><div class="myclass"><!--test_comment--></div></div>
STR;
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$node = $xpath->query('//comment()');
$myComment = $node->item(1)->textContent; // <!--test_comment-->
$myNode = $node->item(1)->parentNode->nodeName; // div
echo $node->item(1)->parentNode->nodeValue; //NOT WORKING
echo "<" . $myNode . ">" . $myComment . "</" . $myNode . ">";
?>
<div>test_comment</div>
<?php
$dom = new DOMDocument;
$dom->loadHTML(data());
$xpath = new DOMXPath($dom);
$node = $xpath->query('//*[comment()]');
foreach( $node as $p ) {
echo 'output: ', $dom->saveXML($p), "\r\n";
}
function data() {
return <<< STR
<div><span id="myid" style="color:blue;font-weight:bold"><!--test--></span><p>no comment here</p><div class="myclass"><!--test_comment--></div></div>
STR;
}
output: <span id="myid" style="color:blue;font-weight:bold"><!--test--></span>
output: <div class="myclass"><!--test_comment--></div>