---
title: "XML parsing using PHP."  
description: "XML parsing using PHP."  
author: "Revati S Misra"  
published: 2023-08-29  
updated: 2023-09-04  
canonical: https://www.mindstick.com/forum/159719/xml-parsing-using-php  
category: "php"  
tags: ["xml", "php", "xml parsing"]  
reading_time: 2 minutes  

---

# XML parsing using PHP.

[XML parsing](https://www.mindstick.com/articles/742/xml-parser-in-php) using PHP.

## Replies

### Reply by Aryan Kumar

Yes, you can use PHP to parse and manipulate [XML](https://www.mindstick.com/blog/203/working-with-xml-data-in-sql-server) data. Here is a simple example of how to parse an XML file in PHP:

PHP

```plaintext
<?php

// Load the XML file
$xml_data = file_get_contents("data.xml");

// Create a SimpleXMLElement object
$xml_obj = new SimpleXMLElement($xml_data);

// Print the name of the first employee
echo $xml_obj->employee[0]->name;

?>
```

In this example, we first load the XML file into a string variable called `$xml_data`. We then create a SimpleXMLElement object from the `$xml_data` variable. The SimpleXMLElement class is a PHP class that can be used to parse and manipulate XML data.

We then use the `employee` tag to access the employee nodes in the XML file. The `name` attribute of the `employee` tag contains the name of the employee. We then print the name of the first employee using the `echo` statement.

You can also use PHP to create XML data. Here is a simple example of how to create an XML file in PHP:

PHP

```plaintext
<?php

// Create an XML document
$xml_doc = new DOMDocument("1.0");

// Create the root element
$root_element = $xml_doc->createElement("employees");
$xml_doc->appendChild($root_element);

// Create the first employee node
$employee_node = $xml_doc->createElement("employee");
$root_element->appendChild($employee_node);

// Add the name attribute to the employee node
$name_node = $xml_doc->createElement("name");
$name_node->appendChild($xml_doc->createTextNode("John Doe"));
$employee_node->appendChild($name_node);

// Save the XML document to a file
$xml_doc->save("data.xml");

?>
```

In this example, we first create a DOMDocument object. The DOMDocument class is a PHP class that can be used to create and manipulate XML documents.

We then create the root element of the XML document. The root element is the element that contains all of the other elements in the document.

We then create the first employee node. The employee node is a child of the root element.

We then add the `name` attribute to the employee node. The `name` attribute contains the name of the employee.

We then save the XML document to a file called `data.xml`.


---

Original Source: https://www.mindstick.com/forum/159719/xml-parsing-using-php

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
