Need some help here.I am stuck
I have a XML file test.xml :
Code:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<element>
<username>A</username>
<about>
<description>random description</description>
<from>A place on earth</from>
<since>1999</since>
</about>
<person>
<gender>female</gender>
<age>29</age>
<status>single</status>
</person>
<profileImage>url to jpg</profileImage>
</element>
<element>
<username>B</username>
<about>
<description>random description</description>
<from>A place on earth</from>
<since>1999</since>
</about>
<person>
<gender>female</gender>
<age>35</age>
<status>single</status>
</person>
<profileImage>url to jpg</profileImage>
</element>
<element>
<username>C</username>
<about>
<description>random description</description>
<from>A place on earth</from>
<since>1999</since>
</about>
<person>
<gender>female</gender>
<age>18</age>
<status>single</status>
</person>
<profileImage>url to jpg</profileImage>
</element>
<element>
<username>D</username>
<about>
<description>random description</description>
<from>A place on earth</from>
<since>1999</since>
</about>
<person>
<gender>female</gender>
<age>22</age>
<status>single</status>
</person>
<profileImage>url to jpg</profileImage>
</element>
<element>
<username>E</username>
<about>
<description>random description</description>
<from>A place on earth</from>
<since>1999</since>
</about>
<person>
<gender>female</gender>
<age>31</age>
<status>single</status>
</person>
<profileImage>url to jpg</profileImage>
</element>
</root>
My problem with this xml is that usernames are in alphabetical order and i want to sort them by,age for example.I use this code:
Code:
<?php
/////////////////////////////sort xml////////////////////////////////////////////////////
$url = 'test.xml';
$xml = simplexml_load_file($url);
$items = array();
foreach($xml->element as $item) {
$items[] = $item;
};
// Custom sort on the names of the items:
usort ($items, function($a, $b ) {
return strcmp($a->person->age[0] , $b->person->age[0]);
});
foreach ($items as $item) {
echo $item->username . "<br/>" . $item->person->age . "<br/><br/>";
}
?>
The output:
As you can see the elements are now sorted,but how do i save it to a new xml file,test-sorted.xml?I 've tried so many times with so many possible codes and i can't figure it out.I am lost...