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:

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

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?