XPath count()在PHP中为什么对我不起作用?

huangapple go评论104阅读模式
英文:

Why is XPath count() not working for me in PHP?

问题

I am trying to get the amount of all section heading elements (H1,H2,H3,H4,H5,H6) from a document using XPath, e.g.:

$headerCount=$xpath->query("count(//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6])");

I tested above query on http://www.xpathtester.com/xpath with this example and got '6' as result:

<h2>Header 1</h2>
<h2>Header 2</h2>
<h3>Header 2.1</h3>
<h4>Header 2.1.1</h4>
<h2>Header 3</h2>
<h3>Header 3.1</h3>

But when I try to use $headerCount like this:

echo "count: ".$headerCount->textContent;

I get this error:

Undefined property: DOMNodeList::$textContent

DOMNodeList suggests that there is a list of nodes, but I thought it is just one numeric value, such as 6 for the amount of all headers.

Anybody who could shed some light on how I can just get the amount of all headings in a document?

英文:

I am trying to get the amount of all section heading elements (H1,H2,H3,H4,H5,H6) from a document using XPath, e.g.:

    $headerCount=$xpath-&gt;query(&quot;count(//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6])&quot;); 

I tested above query on http://www.xpathtester.com/xpath with this example and got '6' as result:

&lt;h2&gt;Header 1&lt;/h2&gt;
&lt;h2&gt;Header 2&lt;/h2&gt;
&lt;h3&gt;Header 2.1&lt;/h3&gt;
&lt;h4&gt;Header 2.1.1&lt;/h4&gt;
&lt;h2&gt;Header 3&lt;/h2&gt;
&lt;h3&gt;Header 3.1&lt;/h3&gt;

But when I try to use $headerCount like this:

echo &quot;count: &quot;.$headerCount-&gt;textContent;

I get this error:

Undefined property: DOMNodeList::$textContent

DOMNodeList suggests that there is a list of nodes, but I thought it is just one numeric value, such as 6 for the amount of all headers.

Anybody who could shed some light on how I can just get the amount of all headings in a document?

答案1

得分: 1

Your XPath is fine; it's your PHP that requires adjustment (as Alejandro pointed out in a helpful comment).

Use DOMXPath::evaluate instead of DOMXPath::query:

$headerCount=$xpath->evaluate("count(//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6])"); 

Then $headerCount will be just one numeric value, such as 6 for the amount of all headers, as expected.

英文:

Your XPath is fine; it's your PHP that requires adjustment (as Alejandro pointed out in a helpful comment).

Use DOMXPath::evaluate instead of DOMXPath::query:

$headerCount=$xpath-&gt;evaluate(&quot;count(//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6])&quot;); 

Then $headerCount will be just one numeric value, such as 6 for the amount of all headers, as expected.

huangapple
  • 本文由 发表于 2020年1月6日 22:53:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定