XML DOMXPath 搜索
<?xml version="1.0" encoding="UTF-8"?>
<root>
<channel>
<item>
<category>Cat1</category>
</item>
<item>
<category>Cat1</category>
</item>
<item>
<category>Cat2</category>
</item>
<item>
<category>Cat3</category>
</item>
</channel>
</root>
我有这个 xml,我如何获得一个项目的最后一个类别而不重复? 我正在尝试:
<?php
$DOMDocument = new DOMDocument( '1.0', 'utf-8' );
$DOMDocument->preserveWhiteSpace = false;
$DOMDocument->load( 'xml.xml' );
$DOMXPath = new DOMXPath( $DOMDocument );
foreach( $DOMXPath->query('.//channel/item/category[last()]/parent::node()') as $Nodes ){
foreach( $Nodes->childNodes as $Node ){
$RSS[ $Node->nodeName ] = $Node->nodeValue;
}
$RSSContents[] = $RSS;
}
echo '<pre>';
print_r( $RSSContents );
但是返回:
Array
(
[0] => Array
(
[category] => Cat1
)
[1] => Array
(
[category] => Cat1
)
[2] => Array
(
[category] => Cat2
)
[3] => Array
(
[category] => Cat3
)
)
我需要返回最后一个猫 1 + 其他物品
<?xml version="1.0" encoding="UTF-8"?>
<root>
<channel>
<item>
<category>Cat1</category>
</item>
<item>
<category>Cat1</category>
</item>
<item>
<category>Cat2</category>
</item>
<item>
<category>Cat3</category>
</item>
</channel>
</root>
i have this xml, how i get last category of one item without repeat ?
i trying:
<?php
$DOMDocument = new DOMDocument( '1.0', 'utf-8' );
$DOMDocument->preserveWhiteSpace = false;
$DOMDocument->load( 'xml.xml' );
$DOMXPath = new DOMXPath( $DOMDocument );
foreach( $DOMXPath->query('.//channel/item/category[last()]/parent::node()') as $Nodes ){
foreach( $Nodes->childNodes as $Node ){
$RSS[ $Node->nodeName ] = $Node->nodeValue;
}
$RSSContents[] = $RSS;
}
echo '<pre>';
print_r( $RSSContents );
But retorning:
Array
(
[0] => Array
(
[category] => Cat1
)
[1] => Array
(
[category] => Cat1
)
[2] => Array
(
[category] => Cat2
)
[3] => Array
(
[category] => Cat3
)
)
i need to return last of cat 1 + other items
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下 XPath 应选择文档中每个类别的最后一项
The following XPath should select the last item of each category in the document