开发者

PHP XML without grouping

I'll be using PHP to parse a SVG-file and I've done some tests with PHP SimpleXML that works very well BUT it groups all the objects with the same type together wich is not good for my SVG.

Say I have SVG file like this:

<svg>
   <g>SOME SVG</g>
   <path d="SOME X AND Y's"/>
   <g>SOME MORE SVG</g>
</svg>

Then Sim开发者_JAVA百科ple XML will group the same objects like:

[g][0] => 'SOME SVG'
[g][1] => 'SOME MORE SVG'
[path[0] => 'SOME AND X AND Y's'

This all works well for editing the data but when I then want to convert it back to SVG again I've lost the sort order of the objects! For normal XML this might not be a problem but for the SVG file the order of objects is also the layer sort order so if I convert the output back to SVG I would get:

<svg>
   <g>SOME SVG</g>
   <g>SOME MORE SVG</g>
   <path d="SOME X AND Y's"/>
</svg>

And then maybe the "SOME MORE SVG"-group will overlap and be on top of the PATH graphics even thought the PATH was supposed to be on top of the "SOME MORE SVG"-group. How do I fix this?

I've seen thats I can add for example order="X" to all objects but since the file have a sort order from the start already, this seems unnecessary. Thank you!


Using PHP DOM, you don't have that problem:

$svg = '<svg>
   <g>SOME SVG</g>
   <path d="SOME X AND Y\'s"/>
   <g>SOME MORE SVG</g>
</svg>';

$dom = new DOMDocument;
$dom->loadXml($svg);

$xpath = new DOMXpath($dom);

// selecting only g nodes directly under svg (root node)
$gNodes = $xpath->query('/svg/g'); // $gNodes will be of type: DOMNodeList with every element being of type: DOMElement, which extends DOMNode

foreach ($gNodes as $gNode) {
    // doing stuff with $gNode
    $gNode->nodeValue .= ' adding stuff';
}

echo $dom->saveXml();

Output:

<?xml version="1.0"?>
<svg>
   <g>SOME SVG adding stuff</g>
   <path d="SOME X AND Y's"/>
   <g>SOME MORE SVG adding stuff</g>
</svg>

Useful links:

  • DOMElement
  • DOMNode
  • DOMNodeList
  • DOMXPath
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜