英文:
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->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?
答案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->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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论