【问题标题】:Loop through SVG elements with PHP [duplicate]使用 PHP 循环遍历 SVG 元素 [重复]
【发布时间】:2013-04-20 01:19:21
【问题描述】:

如何使用 PHP 循环遍历 SVG 元素?

<?php

$svgString = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="overflow: hidden; position: relative;" width="9140" version="1.1" height="3050">
<rect x="0" y="0" width="9140" height="3050" r="0" rx="0" ry="0" fill="#FFFF00" stroke="#000"/>
<image x="-101.5" y="-113.5" width="203" height="227" xlink:href="1.jpg" stroke-width="1"></image>
<image x="-201.5" y="-213.5" width="103" height="127" xlink:href="2.jpg" stroke-width="1"></image>
</svg>';

$svg = new SimpleXMLElement( $svgString );
$result = $svg->xpath('//image');
echo count( $result ); 
for ($i = 0; $i < count($result); $i++) 
{
    var_dump( $result[$i] );
}

count($result) 返回 0,因此省略循环。

我做错了什么?

【问题讨论】:

    标签: php xml xpath svg


    【解决方案1】:

    svg 文档使用默认命名空间:

    <svg xmlns="http://www.w3.org/2000/svg" ...
    

    此外,xlink 命名空间用于 image@href 属性。您需要使用registerXPathNamespace()注册默认命名空间和xlink命名空间:

    $svg = new SimpleXMLElement( $svgString );
    
    // register the default namespace
    $svg->registerXPathNamespace('svg', 'http://www.w3.org/2000/svg');
    // required for the <image xlink:href=" ... attribute
    $svg->registerXPathNamespace('xlink', 'http://www.w3.org/1999/xlink');
    
    // use the prefixes in the query
    $result = $svg->xpath('//svg:image/@xlink:href');
    
    echo count( $result ); // output: '2'
    for ($i = 0; $i < count($result); $i++)
    {
        var_dump( $result[$i] );
    }
    

    【讨论】:

    • 谢谢。我对 xlink:href 有类似的问题。我试过 $svg->registerXPathNamespace('xlink', 'w3.org/1999/xlink');但它似乎不起作用。请问你能帮忙吗?
    • 更新了答案。现在它也使用 xlink 命名空间来获取 href 属性。
    • 当我尝试这样做时,我得到:“警告:SimpleXMLElement::__construct(): 命名空间错误:未定义用于使用 href 的命名空间前缀 xlink ...”:new SimpleXMLElement(' ' );
    • 为什么要这样做:new SimpleXMLElement('&lt;use xlink:href="#MyRect" /&gt;' );?!
    • '' 只是在这里粘贴的一个简短部分。我需要用实际的外部 svg 的内容替换
    【解决方案2】:

    天哪,命名空间:

    $svg = new SimpleXMLElement( $svg );
    $namespaces = $svg->getDocNamespaces();
    $svg->registerXPathNamespace('__nons', $namespaces['']);
    
    $result = $svg->xpath('//__nons:image');
    

    【讨论】:

      猜你喜欢
      • 2021-07-31
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多