SimpleXML:在选择包含命名空间属性的节点时如何获取其他属性


SimpleXML: How do I get other attributes when selecting nodes that contain a namespaced attribute?

选择包含命名空间属性的节点时如何获取其他属性?

我有一个带有 xlink:href 的 SVG ,我正在尝试访问 id 属性,但是在使用 xpath 时,它似乎只返回一个"属性节点"。如何获取实际的"元素节点"?

$xml = new 'SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <image id="my-image" xlink:href="http://example.com/image.png" />
    </svg>
');
$xml->registerXPathNamespace('svg', 'http://www.w3.org/2000/svg');
$xml->registerXPathNamespace('xlink', 'http://www.w3.org/1999/xlink');
$images = $xml->xpath('//svg:image/@xlink:href');
foreach ($images as $image) {
    var_dump($image);
}

输出:

object(SimpleXMLElement)#2 (1) {
  ["@attributes"]=>
  array(1) {
    ["href"]=>
    string(28) "http://example.com/image.png"
  }
}

https://3v4l.org/lvILL

好的,我想通了。正确的路径是:

$images = $xml->xpath('//svg:image[@xlink:href]');

https://3v4l.org/NTcvP