How to Read XML File in PHP Using SimpleXML

What is XML

XML refers to eXtensible Markup Language. The reason XML is called an eXtensible Markup language is that it allows you to define your own element and tag.

The main purpose of XML is to allow sharing of data.  In this tutorial i am using SimpleXML to read the XML file.

I am using my XML file name as blog.xml.

Note – In XML everything is case sensitive. so article and Article both are different thing.

How to Read XML File in PHP Using SimpleXML

To use simpleXML call simplexml_load_file() function , pass file name. It interprets the XML file and converts into an object.Then you can access object properties using standard Object notation.

NOTE: SimpleXML library is available in PHP5 or higher. If you are using older version of PHP then it will not work.

If your print $xml, it will print the object format.

SimpleXML handles element attributes transparently. Attributes-value pairs are represented as members of PHP associative array and can be accessed like regular array elements. In this xml published is an attribute.

Now you can process the object in you PHP file, pick and format the contents as per your requirement.

Conclusion

Parsing XML file through SimpleXML is very simple to use. If you’r looking for object-oriented approach you can check SimpleXMLElement class. If you have any suggestion for an improvement, you are most welcome.

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.