1

Using PHP5 is there a way to query an XML file similar to querying a database? If I had an XML file with 50 hotel entries, how could I query the XML file to get a specific entry? Also could I reorganize the XML entries by field such as a date field? So if I wanted to display the entries in descending date order could I do that?

2 Answers 2

4

Possible by using xpath (simplexml or domxpath)

However to sort is unintuitive

example using simplexml :

$str = '<hotels>
  <hotel>
    <id>1</id>
    <name>Hilton</name>
    <date>2011-01-01</date>
  </hotel>
  <hotel>
    <id>2</id>
    <name>Accor</name>
    <date>2011-01-02</date>
  </hotel>
  <hotel>
    <id>3</id>
    <name>Sands</name>
    <date>2011-01-03</date>
  </hotel>
  ... etc
</hotels>';

$xml = simplexml_load_string($str);

/* find a specic hotel with name=Sands */
$found = $xml->xpath('/hotels/hotel/name[.="Sands"]');

/* order by date */
$sort = array();
foreach ($xml->hotel as $obj)
{
  $sort[(string)$obj->date] = $obj;
}
arsort($sort);
Sign up to request clarification or add additional context in comments.

Comments

1

Meaning if I had a xml file with 50 hotel entries, using PHP5 could I query the xml file to get a specific entry?

Take a look at XPath.

Edit: Ok I shouldn't read so fast, take a look at SimpleXML, this will allow you to load the XML file and perform queries on it, more specifically, look at this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.