PHP SimpleXML 缺少属性

标签 php xml

这不是一个愚蠢的问题。其他人缺少 print_r 中的属性。 但我根本无法访问属性 xlink:href。

这是我尝试过的:

        $xml = simplexml_load_string($imageSVG);           
        $image = $xml->g->image; // works
        $style = $xml->g->image->style; // works
        $style = $xml->g->image['style']; // works
        $remoteHref = $xml->g->image['xlink:href']; // doesn't work
        $remoteHref = $xml->g->image['href']; // doesn't work
        $remoteHref = $xml->g->image->href; // doesn't work
        $array= $xml->g->image->attributes('xlink'); // 0 elements in the array

这是输入的 XML:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="351" height="351" xml:space="preserve"><desc></desc><defs></defs><g transform="translate(145 175) scale(0.4 0.4)"><image xlink:href="http://cdn.katori.com/BfFEEXuBTrii818CNQvN_71344PL.jpg" style="stroke: none; stroke-width: 1; stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); opacity: 1;" transform="translate(-300 -300)" width="600" height="600" preserveAspectRatio="none"></image></g></svg>

谢谢! -马特

最佳答案

attributes 方法需要完整的命名空间,而不仅仅是前缀:

$s = '...';

$xml = new SimpleXMLElement($s);

$attributes = $xml->g->image->attributes('http://www.w3.org/1999/xlink');
echo $attributes['href'];

或者使用attributes的第二个参数(is_prefix - boolean)并仅指定前缀:

$attributes = $xml->g->image->attributes('xlink', true);

Here it is in action.

关于PHP SimpleXML 缺少属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21318688/

相关文章:

php - 带有 "WHERE... IN"查询的 PDO

PHP JQuery 文档准备好添加 IF 语句会中断 .show( )

javascript - 读取 javascript 中的 xsl 变量

c# - 序列化 XML 并保存到 Azure、C#

php - 使用包含两个元素的关联数组在多维数组中搜索唯一行

php - 这个 PHP 随机数库是如何工作的?

php - mysql:将默认值存储为变量

c# - 如何将 XML 读入 DataTable?

xml - Groovy XmlSlurper 访问根节点中的属性值

java - 如何让 DOM 可以读取 xml 文件?