How To Parse XML With PHP
|
Hey guys!
Today I'm going to show you how you can parse XML with PHP. First let's get our XML.You can do it many ways: <?php // Getting XML from string $xml = <<<XML <container> <items> <item>Some stuff</item> <item>Some more stuff</item> </items> </container> XML; // or from file to a string $file = file_get_contents('myXml.xml'); $xml = simplexml_load_string($file); // or from file $xml = simplexml_load_file('myXml.xml'); ?> Now we have our XML stored to $xml variable. Now it's time to parse it. There are many ways to do it, it all depends how you want to parse it. To get first item from items you can get it like this: <?php $file = file_get_contents('myXml.xml'); $xml = simplexml_load_string($file); echo $xml->items[0]->item; ?> Output will be: Some stuff If you want to get second item from items you can do it like this: <?php $file = file_get_contents('myXml.xml'); $xml = simplexml_load_string($file); echo $xml->items[0]->item[1]; ?> Just a reminder.. array starts from 0 so: First item = 0 Second item = 1 Third item = 2 etc... Another way to get items is: <?php $file = file_get_contents('myXml.xml'); $xml = simplexml_load_string($file); echo $xml->{'items'}->item; ?> Output will be: Some stuff If you want to display all items you can do it like this: <?php $file = file_get_contents('myXml.xml'); $xml = simplexml_load_string($file); for($i = 0; $i <= count($xml->items->item); $i++) { echo $xml->items->item[$i].'<br>'; } ?> Or like this for example: <?php $file = file_get_contents('myXml.xml'); $xml = simplexml_load_string($file); foreach($xml->items->item as $x) { echo $x.'<br>'; } ?> For both cases output would be:
So let's make our XML little bit complicated. My XML looks like this now: <container> <items> <item name="Item 1">Some stuff</item> <item name="Item 2">Some more stuff</item> </items> </container> So what if we want to display content for "Item 1".. well it's easy. All you need to do is this: <?php $file = file_get_contents('myXml.xml'); $xml = simplexml_load_string($file); foreach($xml->items->item as $x) { if($x["name"] == 'Item 1') { echo $x; } } ?> Yup, that's that easy.. So I hope it helped you and if you have questions feel free to post a comment below. Take care! I will link PYRAMID with 9 Spokes using 150 mixed links of Forum Profiles, Wikis, Comments.. for $11
|
Replies:
|





















