php - 使用 PHP 遍历 SVG 元素

标签 php xml xpath svg

<分区>

如何使用 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,因此循环被省略。

我做错了什么?

最佳答案

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] );
}

关于php - 使用 PHP 遍历 SVG 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226736/

相关文章:

php - 数组插入mysql行

php - Yii2 将模型保存到数据库

javascript - 如何将 HTML 转换为有效的 XHTML?

XPath/Selenium 无法使用 contains/start-with 的部分 id 来定位元素

php - Symfony 3.1.5 警告:SessionHandler::read(): session 数据文件不是由您的 uid 创建的

c# - 如何正确序列化 DateTime?

android - Tabhost 教程坏了?

java - 使用 XPath 从 WSDL XML 中提取对象列表

python - Xpath:如果包含特定单词,则获取 href

php - Laravel 在注销时清除整个 session