- Code Snippet: Create XML in PHP
- Relevant Content: SimpleXMLElement in PHP
- Scenario: Products Data in PHP Array
- Background and Setup: PHP Array
- Option1: Create XML in PHP with SimpleXMLElement
- Option2: Create XML in PHP with DOMDocument
- Conclusion
- Wrap Up
- Classes and Functions Mentioned
- Want to learn more about PHP?
- How to modify xml file using PHP
- 3 Answers 3
- How to parse XML using php simplexml library
- Want to learn parse XML in php by watching a video?
- XML document structure
- Create a project folder
- Sample XML document
- XML document explanation.
- PHP Code to Parse an XML document
- Summary
Code Snippet: Create XML in PHP
This article explores how to create XML in PHP. Here’s a solution using SimpleXMLElement class.
$products = [ ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40], ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12], ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50], ["Name" => "Cookies", "Price" => 1.5, "Availability" => 80], ]; $root = new SimpleXMLElement(''); foreach($products as $index => $subarray) < $product = $root->addChild('product'); // $product->addAttribute('Id', $index); //Adds an ID attribute to the element product. foreach($subarray as $k => $v ) < $product->addChild($k, $v); //Adds name, price and availability. > > $root->asXML('products.xml');
That’s one obvious option, but that’s not the only one. We will see another class that represents DOM documents in PHP. So, stay tuned to learn something exciting today.
Relevant Content: SimpleXMLElement in PHP
The SimpleXMLElement class represents an XML element and defines the methods necessary to create XML in PHP. We have often used this class in XML-related articles, but here we will focus entirely on building an XML tree from scratch in PHP.
The two most frequently used methods for building an XML tree are
- addChild – Creates a child element
- addAttribute – Creates an element’s attribute.
This article explains how to create XML file with PHP. We will use a tree model illustration to visualize the XML better as we build it dynamically.
Scenario: Products Data in PHP Array
Background and Setup: PHP Array
We need a data source to populate XML elements. Therefore, we will use an array with a few everyday product data. This article is about generating XML tree so we won’t overcomplicate things and keep the source and data as simple as possible.
So, here’s the array of products available in memory.
$products = [ ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40], ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12], ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50], ];
Option1: Create XML in PHP with SimpleXMLElement
First things first, we need to start with a root element. The root element houses the rest of the tree. We need to initialize the SimpleXMLElement object representing the root element, as follows.
$root = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><products/> ');
We have the root element. Here’s the initial tree model with root element only.
The tree will expand as we add children. But how to add data in XML file using PHP? The answer is the products array. So, let’s loop through the array and fetch the data. The succeeding elements will make use of the data.
foreach($products as $index => $subarray) < $product = $root->addChild('product'); // $product->addAttribute('Id', $index); //Adds an ID attribute to the element product. foreach($subarray as $k => $v ) < $product->addChild($k, $v); //Adds name, price and availability. > >
This example is by no means a comprehensive algorithm for transforming an array to XML. To learn more about it, read array to XML in PHP. After the first iteration, the XML tree becomes.
After all the iterations, we create an XML file PHP with asXML method.
Here’s the output in an XML file.
<?xml version="1.0" encoding="UTF-8"?> <products> <product <Name>Tomato Ketchup <Price>2 <Availability>40 <product <Name>Men Fragrance <Price>160 <Availability>12 <product <Name>Air Freshner <Price>8 <Availability>50
The tree model finally looks like.
$products = [ ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40], ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12], ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50], ["Name" => "Cookies", "Price" => 1.5, "Availability" => 80], ]; $root = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><products/>'); foreach($products as $index => $subarray) < $product = $root->addChild('product'); // $product->addAttribute('Id', $index); //Adds an ID attribute to the element product. foreach($subarray as $k => $v ) < $product->addChild($k, $v); //Adds name, price and availability. > > $root->asXML('products.xml');
SimpleXMLElement is the most useful class for XML related operations in PHP. But that’s not the only way. Let’s move on to the alternative option of how to generate XML file dynamically using PHP.
Option2: Create XML in PHP with DOMDocument
DOM stands for Document Object Model and it is a standard interface for representing an XML or HTML document or any tree-like model document. SimpleElementXML is based on the same idea but PHP gives a more explicit class DOMDocument for HTML and XML documents.
There are methods for adding children and attributes to an element as follows.
The flow of the program remains the same as in the previous example. Here’s how to create XML file using PHP.
$products = [ ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40], ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12], ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50], ["Name" => "Cookies", "Price" => 1.5, "Availability" => 80], ]; $dom = new DOMDocument('1.0', 'utf-8'); $root = $dom->appendChild($dom->createElement('products')); foreach($products as $index => $subarray) < $product = $root->appendChild($dom->createElement('product')); // $product_attribute = $dom->createAttribute('Id'); $product_attribute->value = $index; $product->appendChild($product_attribute); //Adds an ID attribute to the element product. foreach($subarray as $k => $v ) < $product->appendChild($dom->createElement($k, $v)); //Adds name, price and availability. > > $dom->save('products.xml'); ?>
Here we go! It returns the same output as before. So that’s all about it, let’s jump to conclusion.
Conclusion
Wrap Up
This article demonstrates how to create XML in PHP. We have seen two options and two classes – SimpleXMLElement and DOMDocument for dynamically creating XML file with PHP. The article also includes visual representation of the XML tree as the program builds it up.
Classes and Functions Mentioned
SimpleXMLElement – (PHP 5, 7, 8) This is a core PHP class that helps in representing XML elements in PHP. It includes all the relevant methods necessary to work with XML. It has been included from PHP 5 all the way to PHP 8 and given its utility, it seems this class is here to stay in the future.
DOMDocument – (PHP 5, 7, 80 This is a core PHP class that represents HTML and XML in terms document object model (DOM). This concept is coherent with the tree model that we have seen because DOM treats XML and HTML as tree-based structures. The class seems to be stable and depreciation seems unlikely in the future.
Want to learn more about PHP?
We have many fun articles related to PHP. You can explore these to learn more about PHP.
How to modify xml file using PHP
I want to modify my xml file in PHP based on the following criteria. my xml structure look like this:
Now every time when xml going to modify, with the type attribute. means, on first time search string == «hotels» then data related to hotels will be stored in xml file as above format. Now when again search for hotels is done then it will remove the elements which have child element with value hotels. and search for different query for e.g. schools is done at that time data related to the schools are appended to the xml file. with the data of the hotels. now again search for schools is done then it will remove the element related to schools. Thanks in advance.
Is the «original, complete» data source also xml based? Or is it «only» a SQL database and you want to format the result as xml?
3 Answers 3
You can use the DOMDocument from PHP.
You load your file and than loop trough the childNodes of the document.
load("file.xml"); $root=$dom->documentElement; // This can differ (I am not sure, it can be only documentElement or documentElement->firstChild or only firstChild) $nodesToDelete=array(); $markers=$root->getElementsByTagName('marker'); // Loop trough childNodes foreach ($markers as $marker) < $type=$marker->getElementsByTagName('type')->item(0)->textContent; $title=$marker->getElementsByTagName('title')->item(0)->textContent; $address=$marker->getElementsByTagName('address')->item(0)->textContent; $latitude=$marker->getElementsByTagName('latitude')->item(0)->textContent; $longitude=$marker->getElementsByTagName('longitude')->item(0)->textContent; // Your filters here // To remove the marker you just add it to a list of nodes to delete $nodesToDelete[]=$marker; > // You delete the nodes foreach ($nodesToDelete as $node) $node->parentNode->removeChild($node); echo $dom->saveXML(); ?>
You can save your output XML like this
$dom->saveXML(); // This will return the XML as a string $dom->save('file.xml'); // This saves the XML to a file
To do this parsing in JavaScript you should use jQuery (a small, but powerful library).
You can include the library directly from Google Code Repository.
The library is cross-browser and very small. It should be cached in many cases, because some sites use it from Google Code
$(yourXMLStringOrDocument).find("marker").each(function () < var marker=$(this); var type=marker.find('type').text(); var title=marker.find('title').text(); var address=marker.find('address').text(); var latitude=marker.find('latitude').text(); var longitude=marker.find('longitude').text(); >);
How to parse XML using php simplexml library
In this tutorial, we are going to learn how to parse XML using php simplexml. XML stands for eXtensible Markup Language. XML is used to store and transport data.
This data is both human and machine-readable. It is commonly used for data interchange over the internet. w3.org is responsible for developing efficient ways to exchange XML docs.
Want to learn parse XML in php by watching a video?
XML document structure
XML documents are descriptive and have tree like structure. Unlike HTML, XML documents have custom tags. It has a root or parent element. Root element have child elements. Child elements can have further child elements. Elements have start and end tags. Inside tags elements can have data and attributes. XML document always starts with .
Create a project folder
Open root folder of your XAMPP or WAMP and add a folder parse-xml-using-php.
Sample XML document
An example XML document is as follows. Create an XML file in project folder books.xml and add the code below into it.
Gambardella, Matthew Computer 44.95 2000-10-01 An in-depth look at creating applications with XML. Ralls, Kim Fantasy 5.95 2000-12-16 A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. Corets, Eva Fantasy 5.95 2001-09-10 The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy.
XML document explanation.
In above XML file, you can view parent books> element. There are many items inside root element. Each book element has further child elements like author, title , genre, price, publish date, description. Each book element has an attribute id. child elements like author, title, genre, price, publish_date, description have data between start and end tag.
PHP Code to Parse an XML document
Create a file index.php and add code below for parsing an XML document.
Books List from XML Document'; $booksList .= '
# | Title | Author | Category | Price | Publish Date | Description |
---|---|---|---|---|---|---|
".$serial." | ".$title." | ".$author." | ".$genre." | ".$price." | ".$pdate." | ".$desc." |
Code explanation
So at first you will use the simplexml_load_file function to load XML document. XML document is loaded into memory in $books variable. We create a variable $booksList and start creating a table with Title, Author, Category, Price, Publish Date and Description headings.
Then in foreach ($books as $bookinfo): loop each book element data such as title, author, category, price, publish_date and description is concatenated with $booksList variable inside a and elements. After end of foreach loop, XML document parsed information inside $booksList element is displayed. The image below displays books list parsed from XML doc.
Using SimpleXML library we can easily parse XML document.
Summary
In this tutorial, you have learned to parse XML using PHP SimpleXML library. You can find source code and example XML file on Github. Click this link to download or clone git repo on your system.
In order to run this script. Copy the project folder in your XAMPP or WAMP root or www folder. Open browser and type URL: http://localhost/parse-xml-using-php/
Please leave your valuable feedback and comments and thanks for reading.