Flourish PHP Unframework
This is an archived copy of the forum for reference purposes

fXML Example

posted by gabrielu 9 years ago

I noticed that there wasn't any example on fXML() that helped Me read an XML document and dumping/exposing the $xml variable didn't really give me anything to work with. So below is an example of an XML document and code for reading it in hopes that it helps someone.

$xml_str = <<<END
<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology 
      society in England, the young survivors lay the 
      foundation for a new society.</description>
   </book>
</catalog>
END;

$i = 0;
$xml = new fXML($xml_str);
foreach($xml->xpath("/catalog/book") as $book) {
	echo ++$i,': ',$book->author,"\\n";
}

thanks for this example but there is 4 hours that i try to access the attribute of an xml but that dont work in your example i try to access the id of the book <book id="bk103"> there is any trick to solve this

sorry for my english

posted by karev 8 years ago

The fXML page includes an example of getting an attribute:

echo $book['id'];

Obviously if your XML contains more than just the <book> tag then you will need some code until you get the $book variable. If you post your XML I can give you a more complete example.

posted by wbond 8 years ago

Sorry, I just realized you are using the XML in the example above. :-) In that case the following code will return the id followed by a : followed by the author's name.

foreach($xml->xpath("/catalog/book") as $book) {
    echo $book['id'], ': ', $book->author, "\\n";
}
posted by wbond 8 years ago

ohh thank's for the help it work ,have a good day PS : i just used this xml example juste for training XD

posted by karev 8 years ago