Jump to content

Sorting XML within PHP


jah-dev

Recommended Posts

Hi,After a fair bit of searching, I'm pretty sure there isn't an easy way to do this...If I store the following tree in a simple xml object...

<list>  <object>    <name>C</name>  </object>  <object>    <name>A</name>  </object>  <object>    <name>B</name>  </object></list>

but I need to sort <object> by the value of <name> before I output the data to the page... how can I do this?Thanks in advance for any help :) Julian

Link to comment
Share on other sites

Hi!First, how you do that depends on howw you "store" the xml-structure in your script.I would think that the easiest way to accomplish that is to "transform" (using foreach or whatever) the structure (may it be DOM or SimpleXML etc.) to a "pure hieracal hashmap/array" (you could use the name as the key) and then use uksort() or uasort() to sort the array using a function that compares the name-values.OR, you could write your own sorting-function, but that would be real complicated...Hope that helped...Good Luck and Don't Panic!

Link to comment
Share on other sites

It's pretty damn easy with XSLT:

<?xml version="1.0"?><stylesheet version="1.0" xmlns="http://www.w3.org/1999/XSL/Transform">	<template match="/list">		<copy>			<apply-templates select="object">				<sort select="name"/>			</apply-templates>		</copy>	</template>	<template match="*">		<copy>			<apply-tempates/>		</copy>	</template></stylesheet>

Save the above as "sort.xsl" (for example) and if your file was called "test.xml", use this PHP file to call it (in the sample, all files are in the same folder):

<?php$xml = new DomDocument;$xml->load('test.xml');$xsl = new DomDocument;$xsl->load('sort.xsl');$xslt = new Xsltprocessor;$xslt->importStylesheet($xsl);$transformation = $xslt->transformToXml($xml);echo $transformation;?>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...