[英]Sort XML nodes with PHP
I have a serialized string comming in with POST: 我有一个与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? 在此示例中,001在003之后重新排序。如何用此新命令更新XML文件? I think I need simpleXML or xpath.
我想我需要simpleXML或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);
Changing the order of nodes amounts to the transformation of XML. 更改节点的顺序相当于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);
XSLT is a right way but you can use XPath+array. XSLT是正确的方法,但是您可以使用XPath + array。 First step - select keys (attributes or anything else), put them into an array, then sort it with standard PHP methods.
第一步-选择键(属性或其他任何键),将它们放入数组中,然后使用标准PHP方法对其进行排序。 Second step - use the array as a key map to make new XML.
第二步-使用数组作为键映射来制作新的XML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.