Flavio
Flavio

Reputation: 31

How to order (sort) a numeric value using simpleXML and PHP

I am extracting data from an XML Engine using simplexml, and I am completely stuck when I try to oder ASC or DESC the data.

Be aware that I am not writing this values myself, but I am extracting them from another source.

Ive got another response to a similiar question and I had this as an example (which works):

$d =  new SimpleXMLElement('<root>
  <item>
    <price>1234</price>
  </item>
  <item>
    <price>4123</price>
  </item>
  <item>
    <price>3142</price>
  </item>
  <item>
    <price>2431</price>
  </item>
</root>');
$items = array();
foreach($d->item as $item) $items[] = $item;
function _mysort($a,$b){return $a->price - $b->price;}
usort($items,'_mysort');
var_dump($items);

The problem is that I don't know how to write the data into the root /item /price.... part automatically.

This is a hotel search engine some hotels pay to be first, but I want the user to be able to see the hotels by price ASC or DESC, so I think I should list the hotels on memory on the server (sorry, i lack the coder slang) and then order them by price and print them.

Any chance I can get some help?

This is what I am doing:

assigning a var to the ur

$url ="http://www.somedomain.com/cgi/xml/engine/get_data.php?ref=$ref&checkin=$checkin&checkout=$checkout&rval=$rval&pval=$pval&country=$country&city=$city&lg=$lg&sort=desc";

Creating my new SimpleXML

$all = new SimpleXMLElement($url, null, true);

Doing a loop to show all hotels:

foreach($all as $hotel) // loop through our hotels {

and echoing the results with the hotels, including price, description, name, address, etc.

echo <<<EOF

If anyone around can help me or show me how to write the xml values into the example I think I am done!

Upvotes: 1

Views: 604

Answers (1)

Martin
Martin

Reputation: 10563

Your question is not very clear.

I assume that you are returned an XML file from your url. You then traverse it and fetch the elements out of it.

I suggest you have a look at this post, which may help you solve your question.

Alternatively you may want to fetch each XML value and store these in a php stdClass, then you can sort that object according to any field.

Upvotes: 1

Related Questions