通过XPATH获取与属性匹配的XML字段的值

时间:2017-04-28 16:02:31

标签: php xml xpath

我有一个非常奇怪的XML架构,这让我感到悲伤和悲伤。

我需要获取具有“隐藏”属性的 IMAGEFILENAME 节点的值。

XML架构类似于:

<PHOTOS>
    <IMAGETHUMBFILENAME/>
    <IMAGECAPTION>
        This is a caption
    </IMAGECAPTION>
    <PRINTQUALITYIMAGE>
        /mylocation/filename1.jpg
    </PRINTQUALITYIMAGE>
    <IMAGEFILENAME pictype="show">
        /mylocation/filename2.jpg
    </IMAGEFILENAME>
    <IMAGETHUMBFILENAME/>
    <IMAGECAPTION>This is another caption</IMAGECAPTION>
    <PRINTQUALITYIMAGE>
        /mylocation/filename3.jpg
    </PRINTQUALITYIMAGE>
    <IMAGEFILENAME pictype="hide">
        /mylocation/filename4.jpg
    </IMAGEFILENAME>
    <IMAGETHUMBFILENAME/>
</PHOTOS>

我已经设法使用PHP提出以下XPATH:

$nodes = $xml->xpath('/PHOTOS/IMAGEFILENAME[@pictype="hide"]');
var_dump($nodes);

当我转储$ nodes var时,我希望看到(以及我想要的)是获取值 /mylocation/filename4.jpg 。相反,我得到的是:

array(1) {
  [0]=>
  object(SimpleXMLElement)#333 (1) {
    ["@attributes"]=>
    array(1) {
      ["pictype"]=>
      string(10) "hide"
    }
  }
}

我尝试了 / parent / text() / node()的各种组合,但根本没有任何乐趣。

请有人告诉我我是一个什么样的布偶,让我摆脱痛苦。架构是否有问题?

1 个答案:

答案 0 :(得分:1)

所以,你有SimpleXMLElements数组。

要获得SimpleXMLElement的字符串表示,您只需echo

$nodes = $xml->xpath('/PHOTOS/IMAGEFILENAME[@pictype="hide"]');
echo $nodes[0];   // I used `[]` notation to get first element of array

要在代码中稍后使用SimpleXMLElement的字符串表示形式,您可以将其明确地转换为字符串:

$nodes = $xml->xpath('/PHOTOS/IMAGEFILENAME[@pictype="hide"]');
$node_str = strval($nodes[0]);  // still `[]` notation