Friday, March 23, 2007

Create and load XML in PHP

This is a tutorial for creating a new XML file from PHP and loading the XML file.
This tutorial has two files generatexml.php and loadfeeds.php

Requirements:
1. PHP5
2. Apache
The XML files are generated in PHP with the help of DOM. The following are the PHP codes

Creating an XML :
Create a PHP file with the name generatexml.php and copy and paste the code in it

$dom = new DOMDocument("1.0");

//create the root node of the XML file
$root = $dom->appendChild($dom->createElement("demo"));

// this is used to create the FRONTEND node
$frontend = $root->appendChild($dom->createElement("frontend"));
//chlids of frontend node
//first node
$flash = $frontend->appendChild($dom->createElement("app"));
$flash->appendChild($dom->createTextNode("Flash"));
//second node
$ajax = $frontend->appendChild($dom->createElement("app"));
$ajax->appendChild($dom->createTextNode("Ajax"));

// this is used to create the SERVERSIDE node
$serverside = $root->appendChild($dom->createElement("serverside"));
//chlids of frontend node
//first node
$php = $serverside->appendChild($dom->createElement("app"));
$php->appendChild($dom->createTextNode("PHP"));
$php->setAttribute("type","opensource");
//second node
$rails = $serverside->appendChild($dom->createElement("app"));
$rails->appendChild($dom->createTextNode("Ruby on Rails"));

// this is used to create the BACKEND node
$backend = $root->appendChild($dom->createElement("backend"));
//chlids of frontend node
//first node
$mysql = $backend->appendChild($dom->createElement("app"));
$mysql->appendChild($dom->createTextNode("MySQL"));
$mysql->setAttribute("type","opensource");
//second node
$postgres = $backend->appendChild($dom->createElement("app"));
$postgres->appendChild($dom->createTextNode("PostgreSQL"));

//save the XML file created
$dom->formatOutput = true;
$dom -> save("demo.xml");

Loading an XML :
Create a PHP file with the name loadfeeds.php and copy and paste the code in it

$dom = new DOMDocument("1.0");
header("Content-Type: text/xml");
$dom ->load( 'demo.xml' );
echo $dom ->saveXML();

First execute generatexml.php to create a xml file "demo.xml" in the current directory.
Then execute loadfeeds.php to load the xml file

No comments: