php 带三个条件的Simplexml:xpath

k10s72fa  于 2023-02-21  发布在  PHP
关注(0)|答案(2)|浏览(119)

我有这样一个xml文件:

<rss version="2.0" xmlns:atom="https://www.w3.org/2005/Atom">
<channel>
<item>
    <city>London</city>
    <description>Trip</description>
    <link>page.php</link>
    <img>img.jpg</img>
</item>
<item>
    <city>London</city>
    <description>Trip</description>
    <link>page.php</link>
    <img>img.jpg</img>
</item>
<item>
    <city>Paris</city>
    <description>Trip</description>
    <link>page.php</link>
    <img>img.jpg</img>
</item>
.
.
</channel>
</rss>

如果我想选择TRIP in LONDON,我可以这样做:

<?php
$xml   = simplexml_load_file('file.xml');
$items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]]');
foreach($items as $item){
echo ' txt ';
}
?>

如果我只想选择在伦敦的第一次旅行,我这样做:

<?php
$xml   = simplexml_load_file('file.xml');
$items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]]')[0];
foreach($items as $item){
echo ' txt ';
}
?>

我也尝试用1代替0
[位置()= 0]
它不起作用。
怎么啦?
我一直在找,我只用位置过滤器做了几次测试,例如:

<?php  
$xml   = simplexml_load_file('site-alpha.xml');
$items = $xml->xpath('//(/item)[1]');
foreach($xml->channel->item as $item){
echo '<div>....</div>';
}
?>

但它不起作用。
我想我对这部分有问题,但我不知道是哪里。

mdfafbf1

mdfafbf11#

<?php
// Load the XML file
$xml = simplexml_load_file('your_xml_file.xml');

// Iterate through each "item" element
foreach ($xml->item as $item) {
    // Output the description and city
    echo $item->description . ' in ' . $item->city . '<br>';
}
?>
f2uvfpb9

f2uvfpb92#

与php不同的是xpath indexing start from "1"
所以这两种方法中的任何一种都只能让你完成第一次旅行:

#indexing is indicated inside the xpath expression so it starts with 1:
$items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]][1]');

#indexing is indicated outside the xpath expression so it's handled by php and  starts with 0:
$items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]]')[0];

相关问题