Jump to content

Sorting XML within PHP

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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...