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 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错