doushi9780 2011-06-14 07:59
浏览 19
已采纳

没有分组的PHP XML

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 Simple 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!

  • 写回答

1条回答 默认 最新

  • douyou1857 2011-06-14 08:15
    关注

    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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图