使用PHP对XML节点进行排序 [英] Sort XML nodes with PHP

查看:86
本文介绍了使用PHP对XML节点进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与POST一起输入的序列化字符串:

I have a serialized string comming in with POST:

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

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

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

推荐答案

更改节点的顺序等同于XML的转换.你可以做这样的事情,

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

这篇关于使用PHP对XML节点进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆