I am getting a "Trying to get property of non-object" error when using the following code to get the next div id sibling (the div id sibling after 'div id = "XXX"'. Could someone please tell me how to correct it? Thanks
$Html ='<div id="currency">
<a href="http://www.link.com/313">
<div class="sub_item">
<h3>Sub Categ A</h3>
</div>
</a>
</div>
<div id="Next-Sibling">
<a href="http://www.link.com/111">
<div class="sub_item">
<h3>Sub Categ A</h3>
</div>
</a>
</div>'
function GetNextSibling(){
$doc = new DOMDocument();
@$doc->loadHTML($Html);
$xpath = new DOMXpath($doc);
$els = $xpath->query('.//div[@id="currency"]/following-sibling::div[1]/@id');
print_r ($els[0]->nodeValue); //Wanting result "Next-Sibling"
}
My Answer:
bit confused by your question. Are you asking how to use PHP and XPath to get the next sibling element from an HTML source? If so, you can use the following code snippet:
php
$html = 'First paragraph
Second paragraph
Third paragraph
';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$node = $xpath->query('//p[text()="Second paragraph"]')->item(0);
$nextSibling = $node->nextSibling;
if ($nextSibling) {
echo $doc->saveHTML($nextSibling);
} else {
echo 'No next sibling found';
}
In this code snippet, we first load the HTML source into a `DOMDocument` object and create a `DOMXPath` object to query the document using XPath. We then select the element with the text "Second paragraph" and get its next sibling element. Finally, we check if a next sibling exists and output its HTML content if it does.
Rate this post
3 of 5 based on 1744 votesComments