Blade
Blade

Reputation: 1437

How to put XML content in reverse order?

I tried a few solutions already posted here, but nothing seems to work. That might be, because I am really not that familiar with php or xml. I just need to output xml for xcoding. So hopefully someone can shed some light, on how I can reverse the order of my xml, so that the last entry is on top. My last try what with:

$query = array_reverse($doc->xpath('query'));

but it did not like it ,e.g. it did not work.

So here is my code in order to create my xml document:

<?php 

if(!$dbconnect = mysql_connect('localhost', '-', '-')) {
echo "Connection failed to the host 'localhost'.";
exit;
} // if
if (!mysql_select_db('-')) {
echo "Cannot connect to database '-'";
exit;
} // if

$table_id = 'table1';
$query = "SELECT Name,Age,Sex FROM $table_id";

$dbresult = mysql_query($query, $dbconnect);

// create a new XML document
$doc = new DomDocument('1.0');

// create root node
$root = $doc->createElement('root');
$root = $doc->appendChild($root);

// process one row at a time
while($row = mysql_fetch_assoc($dbresult)) {

// add node for each row
$occ = $doc->createElement($table_id);
$occ = $root->appendChild($occ);

// add a child node for each field
foreach ($row as $fieldname => $fieldvalue) {

$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);

$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);

} // foreach
} // while


// get completed xml document
$xml_string = $doc->saveXML();
$doc->save("yolo.xml") 

//echo $xml_string;
?> 

Upvotes: 0

Views: 433

Answers (1)

Francis Avila
Francis Avila

Reputation: 31621

The best thing to do is to issue an SQL query which returns results in the order you want. The SQL query you have here has no ORDER BY clause, so results come back in no particular order.

However, you can also reverse the order of results as you add them to your XML document: instead of appending new child nodes for each row, prepend them. Replace this line:

$occ = $root->appendChild($occ);

With

$occ = $root->insertBefore($occ, $root->firstChild);

Also generally speaking it's best to finish building a tree of XML before you add it to the document.

Upvotes: 1

Related Questions