【问题标题】:Getting an XML value from a named field从命名字段中获取 XML 值
【发布时间】:2019-02-15 00:30:12
【问题描述】:

很抱歉问这个问题,但这让我发疯了。 我一直在使用 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";
}

【问题讨论】:

  • var_dump($sxml) ?
  • Xpath 从 [1] 开始计数,但不为零

标签: php xml xpath simplexml


【解决方案1】:

以防万一您要查找的节点位于某个位置很深,您可以在开头添加一个双斜杠。

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

如果您有多个 &lt;nowplaying-info&gt; 元素,也是如此。您可以为此使用索引。 (注意 [1] 索引)

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

【讨论】:

    【解决方案2】:

    您的 xpath 表达式非常正确,但您不需要为 &lt;nowplaying-info-list&gt; 元素指定索引 - 它会自行处理。如果您要提供索引,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 的情况下执行此操作,您需要遍历每个 &lt;property&gt; 元素,并测试它们的 name 属性。

    【讨论】:

    • 谢谢。你的例子真的很有帮助。我最终要做的(根据链接的示例)是使用 simplexml_load_string,而不是 $sxml = new SimpleXMLElement($raw_xml);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多