在PHP中修改SVG和子属性

时间:2019-06-21 16:57:07

标签: php xml dom svg

我有一个要略微修改的SVG:

$svgData = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <title>railroad-train-1</title>
    <path
        d="M6.555,18.418a1,1,0,0,0-1.387.277l-2.5,3.75a1,1,0,0,0,1.664,1.11l2.5-3.75A1,1,0,0,0,6.555,18.418Z"
    ></path>
    <path d="M21.332,22.445l-2.5-3.75a1,1,0,1,0-1.664,1.11l2.5,3.75a1,1,0,0,0,1.664-1.11Z"></path>
    <path
        d="M20,15V4.511A4.516,4.516,0,0,0,15.489,0H8.511A4.516,4.516,0,0,0,4,4.511V15a2.23,2.23,0,0,0,1.8,2.192A34.368,34.368,0,0,0,12,18a34.407,34.407,0,0,0,6.211-.81A2.218,2.218,0,0,0,20,15ZM13,2.25A.25.25,0,0,1,13.25,2h2.239A2.513,2.513,0,0,1,18,4.511V8.34a.25.25,0,0,1-.306.244,24.753,24.753,0,0,0-4.454-.561.251.251,0,0,1-.24-.25ZM6,4.511A2.513,2.513,0,0,1,8.511,2H10.75a.25.25,0,0,1,.25.25V7.773a.251.251,0,0,1-.24.25,24.753,24.753,0,0,0-4.454.561A.25.25,0,0,1,6,8.34ZM7.75,13H6.25a.5.5,0,0,1-.5-.5v-1a.5.5,0,0,1,.5-.5h1.5a1,1,0,0,1,0,2Zm6.5,2.852a.251.251,0,0,1-.22.249A17.606,17.606,0,0,1,12,16.25,17.606,17.606,0,0,1,9.97,16.1a.251.251,0,0,1-.22-.249V14a.253.253,0,0,1,.25-.25h4a.253.253,0,0,1,.25.25ZM17.75,13h-1.5a1,1,0,0,1,0-2h1.5a.5.5,0,0,1,.5.5v1A.5.5,0,0,1,17.75,13Z"
    ></path>
</svg>';
$iconSVG = new \DOMDocument();
$iconSVG->loadXML($svg_data);
$svgTag = $iconSVG->getElementsByTagName("svg");
$svgTag->setAttribute('role', 'img');
$svgTag->setAttribute('fill', 'white');
$titleTag = $iconSVG->getElementsByTagName("title");
$titleTag->nodeValue = 'my custom title';
$items[$i]['iconSVG'] = $iconSVG->saveXML($iconSVG->documentElement);

..但是出现此错误,所有修改均无效:

Fatal error: Call to undefined method DOMNodeList::setAttribute()

1 个答案:

答案 0 :(得分:1)

调用getElementsByTagName()时-这会为您提供匹配节点的列表(因此DOMNodeList),但是由于您期望只找到1个,因此可以使用$svgTag[0]。 / p>

以后可以使用$titleTag[0]->nodeValue

$iconSVG = new \DOMDocument();
$iconSVG->loadXML($svgData);
$svgTag = $iconSVG->getElementsByTagName("svg");
$svgTag[0]->setAttribute('role', 'img');
$svgTag[0]->setAttribute('fill', 'white');
$titleTag = $iconSVG->getElementsByTagName("title");
$titleTag[0]->nodeValue = 'my custom title';