使用PHP提取多个特定的XML属性

时间:2013-02-06 19:30:06

标签: php xml

我正在尝试从一个软件生成的XML文件中提取几个属性,但我没有运气。

到目前为止我的代码看起来像这样;

$xml_feed_url = 'http://localhost/rest/getNowPlaying.view?u=USERNAMEt&p=PASSWORD&v=1.8.0&c=test';  
$ch = curl_init();  
curl_setopt($ch, CURLOPT_URL, $xml_feed_url);  
curl_setopt($ch, CURLOPT_HEADER, false);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
$xml = curl_exec($ch);  
curl_close($ch); 
echo $xml;

此代码成功输出以下XML文件;

<?xml version="1.0" encoding="UTF-8"?>
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.8.0">  
  <nowPlaying>  
    <entry id="1805" parent="1798" title="Too Close" album="The Lateness Of The Hour" artist="Alex Clare" isDir="false" coverArt="1798" created="2012-05-22T13:12:29" duration="256" bitRate="320" track="4" discNumber="1" year="2011" genre="Pop" size="10283678" suffix="mp3" contentType="audio/mpeg" isVideo="false" path="Alex Clare/The Lateness Of The Hour/Alex Clare - Too Close.mp3" albumId="50" artistId="14" type="music" username="RestClient" playerId="8" minutesAgo="0"/>  
    <entry id="33664" parent="33642" title="Hot Ride" album="Always Outnumbered, Never Out Gunned" artist="The Prodigy" isDir="false" coverArt="33642" created="2012-05-10T00:31:16" duration="276" bitRate="128" track="5" discNumber="1" year="2004" genre="Other" size="5135448" suffix="mp3" contentType="audio/mpeg" isVideo="false" path="The Prodigy/Always Outnumbered, Never Out Gunned/The Prodigy - Hot Ride.mp3" albumId="2064" artistId="635" type="music" username="Revenant" playerId="6" playerName="test" minutesAgo="3"/>  
  </nowPlaying>  
</subsonic-response>

我能够使用foreach循环(下面)成功提取特定属性,但我希望从一个用户中提取特定的多个属性,而不是全部。

foreach($xml->children()->children() as $second_gen){  
echo "User: ".$second_gen['username'];  
echo "Artist: ".$second_gen['artist'];  
echo "Title: ".$second_gen['title'];  
echo "Album: ".$second_gen['album'];

任何想法都将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

如何使用simple_xml和XPath?

像...一样的东西。

$username='Revenant';
$xml->registerXPathNamespace("n", "http://subsonic.org/restapi");
$result=$xml->xpath("//n:entry[@username='$username']/@title | //n:entry[@username='$username']/@album | //n:entry[@username='$username']/@artist");

echo "$result[0] by $result[2] on the album $result[1]";

使用PHP 5.4.4进行测试

道之