Search code examples
xpathdomdocument

XPath Sibling returns empty


I'm using this http://www.xpathtester.com/xpath/5a30592045b6aa5089faf909261ede0b XPath tester, which returns exactly what I want. For some reason it removes my full query, but if you use it, it works.

*/h3[contains(string(), "Description")]/following-sibling::p[1]

But in real life, I get nothing from my variable.

I'm trying to get the data after <h3>Description</h3>, in this case a paragraph <p>.

HTML $feed_item=

<div class="outer-feed"><ul>
<li><strong>Severity:</strong> <span class="label label-info">Low</span></li>
</ul>
<h3>Description</h3>
<p>The lack of validation of configuration parameters used in SQL queries caused various SQL injection vectors.</p>
...

Here's my XPath

$description_node = $xpath->query('*/h3[contains(string(), "Description")]/following-sibling::p[1]', $feed_item);
$description = "description: " . $description_node->item(0)->textContent;

and var_dump

object(DOMNodeList)#1654 (1) { ["length"]=> int(0) }

And the error

Notice
: Trying to get property 'textContent' of non-object in

What confuses me is that I can get Severity from the same HTML by using this:

$severity_node = $xpath->query('*/li[contains(string(), "Severity:")]', $feed_item);
$severity = preg_replace('/Severity:\W*/u', '', $severity_node->item(0)->textContent);

My first thought was to scale back to just the H3 and output that.

$description_node = $xpath->query('*/h3[contains(string(), "Description")]', $feed_item);
object(DOMNodeList)#1654 (1) { ["length"]=> int(0) } // doesn't contain anything

Given that the following are identical but the first works and the second doesn't, what could be the problem?

$severity_node = $xpath->query('*/li[contains(string(), "Severity:")]', $feed_item);
$description_node = $xpath->query('*/h3[contains(string(), "Description")]', $feed_item);

Why is one working and not the other. And what is the best way to troubleshoot things like this. It seems to work on the xpathtester. What could I be doing wrong that causes this problem in PHP?


Solution

  • Try with this XPath:

    //h3[text()="Description"]/following::p[1]