SimpleXML:在选择包含命名空间属性的节点时如何获取其他属性?
SimpleXML: How do I get other attributes when selecting nodes that contain a namespaced attribute?
在选择包含命名空间属性的节点时如何获取其他属性?
我有一个带有 xlink:href
的 SVG,我正在尝试访问 id
属性,但是在使用 xpath 时它似乎只有 return 和 "attribute node"。我如何获得实际的 "element node"?
$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"
}
}
好的,我明白了。正确的 xpath 是:
$images = $xml->xpath('//svg:image[@xlink:href]');
在选择包含命名空间属性的节点时如何获取其他属性?
我有一个带有 xlink:href
的 SVG,我正在尝试访问 id
属性,但是在使用 xpath 时它似乎只有 return 和 "attribute node"。我如何获得实际的 "element node"?
$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"
}
}
好的,我明白了。正确的 xpath 是:
$images = $xml->xpath('//svg:image[@xlink:href]');