dongshi1934 2010-05-07 12:12
浏览 100
已采纳

使用PHP对XML节点进行排序

I have a serialized string comming in with POST:

$imgdata = $_POST['imgdata']; // li[]=2&li[]=3&li[]=1&li[]=4

In this example 001 is reordered after 003 How can I update my XML file with this new order? I think I need simpleXML or xpath. Here are my thoughts:

// 1. load xml string
$xml = simplexml_load_file('test.xml');
/*
<?xml version="1.0" encoding="UTF-8"?>
<gallery>
    <album>
        <img src="001.jpg" caption="First caption" />
        <img src="002.jpg" caption="Second caption" />
        <img src="003.jpg" caption="3th caption" />
        <img src="004.jpg" caption="4th caption" />
    </album>
</gallery>
*/

// 2. sort nodes
// $new_xml_string = "......";

// 3. write out new XML file
$handle = fopen("images.xml", 'w');
fwrite($handle, $new_xml_string);
fclose($handle);
  • 写回答

2条回答 默认 最新

  • dongsu4345 2010-05-07 14:49
    关注

    Changing the order of nodes amounts to the transformation of XML. You can do something like this,

    <?php
    
    $temp = <<<EOT
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
         version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="node() | @*">
      <xsl:copy>
        <xsl:apply-templates select="node() | @*">
          <xsl:sort select="@src"/>
        </xsl:apply-templates>
      </xsl:copy>
    </xsl:template>
    </xsl:stylesheet>
    EOT;
    
    
    $xml = new DOMDocument;
    $xml->loadXML($oldXml);
    $xsl = new DOMDocument;
    $xsl->loadXML($temp);
    $proc = new XSLTProcessor;
    $proc->importStyleSheet($xsl); // attach the xsl rules
    
    $newXml = $proc->transformToXML($xml);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染