How to create and read the xml using php

How to create and read the xml using php

In this tutorial we given code sample for create and read the xml using php. we given explanation and there details

What is XML?
Extensible Markup Language (XML) is described as both a markup language. Now it is known as data storage format also

How to create and read the xml using php
How to create and read the xml using php

XML is very important in in today’s application development environment.
If you’ve never before worked with XML in PHP or have not yet made the jump to PHP5, this starter guide to working with new functionality available in PHP5 for XML.

Using following code you are able to create simple xml file.

<?php

//Creates XML string and XML document using the DOM
$dom = new DomDocument('1.0');

//add root - <books>
$books = $dom->appendChild($dom->createElement('books'));

//add <book> element to <books>
$book = $books->appendChild($dom->createElement('book'));

//add <title> element to <book>
$title = $book->appendChild($dom->createElement('title'));

//add <title> text node element to <title>
$title->appendChild(
$dom->createTextNode('Wordpressapi Magazine'));

//generate xml
$dom->formatOutput = true; // set the formatOutput attribute of
// domDocument to true
// save XML as string or file
$test1 = $dom->saveXML(); // put string in test1
$dom->save('wordpressapi1.xml'); // save as file
?>

Out put of above code will as follows:

<?xml version="1.0"?>
<books>
<book>
<title>Wordpressapi Magazine</title>
</book>
</books>

Now I am going to show you how to read the xml file using php

[/php]
loadXML(‘wordpressapi1.xml’);
if (!$dom) {
echo ‘Error while parsing the document’;
exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title; // WordPressapi Magazine
?>
[/php]

or in other way

$xmlFileData = file_get_contents(“wordpressapi1.xml”);
// Here's our Simple XML parser!
$xmlData = new SimpleXMLElement($xmlFileData);
// output will be shown in array format
print_r($xmlData);

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.