0

我有一个带有 POST 的序列化字符串:

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

在此示例中,001 在 003 之后重新排序 如何使用这个新顺序更新我的 XML 文件?我想我需要 simpleXML 或 xpath。以下是我的想法:

// 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);
4

2 回答 2

3

改变节点的顺序相当于对 XML 的转换。你可以做这样的事情,

<?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);
于 2010-05-07T14:49:24.740 回答
2

XSLT 是正确的方法,但您可以使用 XPath+array。第一步 - 选择键(属性或其他任何内容),将它们放入数组中,然后使用标准 PHP 方法对其进行排序。第二步 - 使用数组作为键映射来制作新的 XML。

于 2011-11-26T19:17:51.790 回答