如何按根标记名称过滤SVG / XML文档?

时间:2013-09-26 01:55:37

标签: php xml svg

如何在给定的SVG文档中仅选择和输出第一个g节点?

这是输入的SVG数据($svg_doc):

<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" width="765" height="990" id="svg2" xml:space="preserve">
<metadata id="metadata8">
    <rdf:rdf>
        <cc:work rdf:about="">
            <dc:format>image/svg+xml</dc:format>
            <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"></dc:type>
        </cc:work>
    </rdf:rdf>
</metadata>
<defs id="defs6"></defs>
<g transform="matrix(1.25,0,0,-1.25,0,990)" id="g10">
    <g id="g11">
        <path d="m 14.875,768.812 0.203,-0.046 -0.687,-2.157 -6.157,0 0,0.219 0.313,0 c 0.332,0 0.57,0.11 0.719,0.328 0.082,0.125 0.125,0.41 0.125,0.86 l 0,5.14 c 0,0.489 -0.059,0.797 -0.172,0.922 -0.157,0.176 -0.383,0.266 -0.672,0.266 l -0.313,0 0,0.218 3.61,0 0,-0.218 c -0.43,0 -0.727,-0.043 -0.891,-0.125 -0.168,-0.086 -0.281,-0.188 -0.344,-0.313 -0.062,-0.125 -0.093,-0.422 -0.093,-0.89 l 0,-5 c 0,-0.325 0.031,-0.543 0.093,-0.657 0.039,-0.086 0.11,-0.148 0.203,-0.187 0.102,-0.043 0.411,-0.063 0.922,-0.063 l 0.578,0 c 0.614,0 1.04,0.047 1.282,0.141 0.25,0.094 0.472,0.25 0.672,0.469 0.207,0.226 0.41,0.593 0.609,1.093 z" id="path14"></path>
    </g>
</g>
<g id="g23"></g>
<g id="g24"></g>
</svg>

我尝试过的PHP代码:

<?php
$dom = new DOMDocument;
$dom->loadXml($svg_doc);
echo $dom->getElementsByTagname('g')->item(0)->value;
?>

结果不好:

Notice: Undefined property: DOMElement::$value in /home/...

这应该是这样的:

<g transform="matrix(1.25,0,0,-1.25,0,990)" id="g10">
    <g id="g11">
        <path d="m 14.875,768.812 0.203,-0.046 -0.687,-2.157 -6.157,0 0,0.219 0.313,0 c 0.332,0 0.57,0.11 0.719,0.328 0.082,0.125 0.125,0.41 0.125,0.86 l 0,5.14 c 0,0.489 -0.059,0.797 -0.172,0.922 -0.157,0.176 -0.383,0.266 -0.672,0.266 l -0.313,0 0,0.218 3.61,0 0,-0.218 c -0.43,0 -0.727,-0.043 -0.891,-0.125 -0.168,-0.086 -0.281,-0.188 -0.344,-0.313 -0.062,-0.125 -0.093,-0.422 -0.093,-0.89 l 0,-5 c 0,-0.325 0.031,-0.543 0.093,-0.657 0.039,-0.086 0.11,-0.148 0.203,-0.187 0.102,-0.043 0.411,-0.063 0.922,-0.063 l 0.578,0 c 0.614,0 1.04,0.047 1.282,0.141 0.25,0.094 0.472,0.25 0.672,0.469 0.207,0.226 0.41,0.593 0.609,1.093 z" id="path14"></path>
    </g>
</g>

仅选择第一个根g节点并输出。

1 个答案:

答案 0 :(得分:1)

尝试使用DOMNode::C14N()方法:

echo $dom->getElementsByTagname('g')->item(0)->C14N(true);

UPDv1:

请改用DOMDocument::saveXML()方法。更可靠。

$node = $dom->getElementsByTagname('g')->item(0);
echo $dom->saveXML($node);