从命名字段获取XML值

问题描述 投票:0回答:2

很抱歉要问这个,但这让我发疯了。我一直在使用php SimpleXMLElement作为我的XML转到解析器,我看了很多例子,并且已经放弃了很多次。但是,现在,我只需要让它工作。有很多关于如何获得简单字段的例子,但是字段中的值不是很多......

我试图从这个XML中获取“track_artist_name”值作为php中的命名变量。

<nowplaying-info-list>
  <nowplaying-info >
    <property name="track_title"><![CDATA[Song Title]]></property>
    <property name="track_album_name"><![CDATA[Song Album]]></property>
    <property name="track_artist_name"><![CDATA[Song Artist]]></property>
  </nowplaying-info>
</nowplaying-info-list>

我尝试过使用xpath:

$sxml->xpath("/nowplaying-info-list[0]/nowplaying-info/property[@name='track_artist_name']"));

但是,我知道这一切都搞砸了,而且没有用。

我最初也尝试过这样的东西,认为它有意义 - 但不是:

attrs = $sxml->nowplaying_info[0]->property['@name']['track_artist_name'];
echo $attrs . "\n\n";

我知道我可以通过以下方式获取值:

$sxml->nowplaying_info[0]->property[2];

有时XML结果中的行数多于其他时间,因此,它会使用错误的数据中断计算。

有人可以解释我的问题吗?我只是想把艺术家的名字变成一个变量。非常感谢。

***工作更新:**

我不知道有不同的XML解释器方法,并使用以下XML解释器版本:

// read feed into SimpleXML object
$sxml = new SimpleXMLElement($json);

这不起作用,但现在已经更新到以下(针对该部分代码),这要归功于此处的帮助。

$sxml_new = simplexml_load_string($json_raw);
if ( $sxml_new->xpath("/nowplaying-info-list/nowplaying-info/property[@name='track_artist_name']") != null )
{
    $results = $sxml_new->xpath("/nowplaying-info-list/nowplaying-info/property[@name='track_artist_name']");
    //print_r($results);
    $artist = (string) $results[0];
   // var_dump($artist); 
    echo "Artist: " . $artist . "\n";
}
php xml xpath simplexml
2个回答
3
投票

你的xpath表达式非常正确,但是你不需要为<nowplaying-info-list>元素指定一个索引 - 它将自己处理它。如果你要提供一个索引,it would need to start at 1, not 0

尝试

$results = $sxml->xpath("/nowplaying-info-list/nowplaying-info/property[@name='track_artist_name']");

echo (string) $results[0];

歌曲艺术家

https://3v4l.org/eH4Dr

你的第二种方法:

$sxml->nowplaying_info[0]->property['@name']['track_artist_name'];

将尝试访问第一个属性元素的名为@name的属性,而不是将其视为xpath样式的@表达式。要在不使用xpath的情况下执行此操作,您需要遍历每个<property>元素,并测试其名称attibrute。


0
投票

如果你正在寻找的节点深深地存在于某些地方,你可以在开始时添加一个双斜杠。

$results = $sxml->xpath("//nowplaying-info-list/nowplaying-info/property[@name='track_artist_name']");

如果你有多个<nowplaying-info>元素也是如此。你可以使用索引。 (注意[1]索引)

$results = $sxml->xpath("//nowplaying-info-list/nowplaying-info[1]/property[@name='track_artist_name']");
© www.soinside.com 2019 - 2024. All rights reserved.