I am very new to coding and I have some practise exercises by my college and the first is to take an XML document and return the data using php which I have managed to do however the next step is to sort that data by either a new child element called 'note_id' or by adding an 'id' attribute to the note element and then show the data in descending order. I went with adding a new child element of note_id and I have inserted note_id number 6 in the middle of the other elements to see if it would sort.
I have tried numerous things by looking up information on the internet however I feel like I am just going round in circles as I am new to this and nothing seems to work (obviously as I don't know what I am doing - but got to start somewhere).
I haven't posted this question just to get an answer, I also need to understand how and why this method works if someone does reply with an answer.
My XML data is shown below and is stored in a file called 'note.xml'.
<?xml version="1.0" encoding="UTF-8"?>
<notes>
<note>
<note_id>1</note_id>
<to>tove1</to>
<from>Jani1</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>2</note_id>
<to>tove2</to>
<from>Jani2</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>3</note_id>
<to>tove3</to>
<from>Jani3</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>6</note_id>
<to>tove6</to>
<from>Jani6</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>4</note_id>
<to>tove4</to>
<from>Jani4</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<note_id>5</note_id>
<to>tove5</to>
<from>Jani5</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
</notes>
My current PHP code is below which brings back the XML.
?php
// Loads the xml file.
$xml= simplexml_load_file("note.xml");
// Returns the top level xml element - notes.
echo $xml->getName() . "<br />";
// Returns each note element.
foreach($xml->note as $note){
echo $note->getName() . ": " . $note . "<br />";
// Returns each child element of note element.
foreach($note->children() as $child){
echo $child->getName() . ": " . $child . "<br />";
}
echo "<br />";
}
echo "<br />";
?>