Sample code for XML parsing with PHP

There are lots of examples on using XML with PHP in the internet. A simple search would provide you a lot of code to work with. For example if you want to load an XML document 'books.xml', then you can use the following code.


_______________________________________________


$domobj = new DomDocument();
$domobj->load("books.xml");

Suppose you want to get all the names of the authors in the XML file, then you can do so by,

$authors = $domobj->getElementsByTagName("author");

The above code would get an array of all the authors available in the XML file. If you want to print out all the authors, then you have to use a foreach loop to print out as given below:

foreach($authors as $authnode) {
print $authnode->textContent . " ";
}

The same example can also be done by using the XPath query to navigate through all the authors in the XML document. This can be done like,

$xptoauthor = new domxpath($domobj);
$authors = $xptoauthor->query("/books/book/author");
foreach ($authors as $authnode) {
print $authnode->txtContent . " ";
}

You can try these samples on your own to have a feel on how easy it is to work with XML and PHP.





_______________________________________________

FREE Subscription

Subscribe to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.

Name:
Email:

Note : We never rent, trade, or sell my email lists to
anyone. We assure that your privacy is respected
and protected.

_______________________________________



 

FREE Subscription

Stay Current With the Latest Technology Developments Realted to XML. Signup for Our Newsletter and Receive New Articles Through Email.

Name:

Email:

Note : We never rent, trade, or sell our email lists to anyone. We assure that your privacy is respected and protected.

 

 

Add to My Yahoo!

Visit XML Training Material Guide Homepage

 

 

Copyright - © 2004 - 2017 - All Rights Reserved.