使用PHP遍历SVG元素 [英] Loop through SVG elements with PHP
本文介绍了使用PHP遍历SVG元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用PHP遍历SVG元素?
How can I loop through SVG elements with PHP?
<?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,因此省略了循环.
count($result)
returns 0 so the loop is omitted.
我在做什么错了?
推荐答案
svg文档正在使用默认名称空间:
The svg document is using a default namespace:
<svg xmlns="http://www.w3.org/2000/svg" ...
此外,xlink命名空间用于image @ href属性.您需要使用 registerXPathNamespace()
注册默认名称空间和xlink名称空间. :
Further, the xlink namespace is used for image@href attributes. You need to register the default namespace and the xlink namespace using registerXPathNamespace()
:
$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] );
}
这篇关于使用PHP遍历SVG元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文