How to Parse XML with PHP

If you are eager to learn to parse XML (Extensible Markup Language) with PHP, you are in the right place.

In this tutorial, we are going to reveal how to do it using the so-called SimpleXML extension. It allows programmers to get the name of an element, its textual content, attributes, and so on.

Watch a course Learn object oriented PHP

So, to parse XML with PHP, you need to act like this:


//simple xml
$xmlData = "<!--?xml version='1.0'?-->
           <type>Server Side</type>
           <type>Client Side</type>

//loading the xml string with simplexml function
$xml = simplexml_load_string($xmlData);

//looping through every node of the molecule
foreach ($xml->language as $language) {
  //node are accessted by -> operator
  echo $language->name, '  ';
  echo $language->type, '<br>';


The Usage of SimpleXML Parser

SimpleXML relates to the tree-based parsers.

It allows turning an XML document into a data structure that can be iterated through like array and object collections. In comparison with DOM, it requires fewer code lines for reading text data from elements.

Starting from PHP 5 version, the functions of SimpleXML are part of the core PHP. It means that there is no need to install one to apply the features.