How to Read XML Using PHP DOM

This simple example mentions how the data from the xml file can be read and displayed in a textbox in the html file. It illustrates the concept which simplifies understanding the basics.

The structure of file.xml is:-


HELLO

This code lies in  file.php:-
<?php
 $xdoc = new DOMDocument( ‘1.0’, ‘UTF-8’ );
$xdoc->Load(“file.xml”);
$candidate = $xdoc->getElementsByTagName(‘root’)->item(0);
$newElement = $xdoc ->createElement(‘root’);
$txtNode = $xdoc ->createTextNode ($root);
$newElement -> appendChild($txtNode);
$candidate -> appendChild($newElement);
$msg = $candidate->nodeValue;
?>

This code lies in file.html



It will display the data in $msg variable in the textbox names msgval.

Advertisements

Creating A Xml Document Using XML DOM And PHP

I had many issues to dealing with while solving this problem i i though about sharing this. The code below illustates a simple logis to create a XML file if it is not present and create a root node. And looking at this node you can create chile nodes.

The code is as follows:-

<?php
$uvar = “HELLO”;
$doc = new DOMDocument(‘1.0’, ‘UTF-8’);
$ele = $doc->createElement( ‘root’ );
$ele->nodeValue = $uvar;
$doc->appendChild( $ele );
$test = $doc->save(“file.xml”)

?>

This will create a file.xml with the following contents:-
HELLO

Design database using XML and evaluate queries.

It is a simple xml demo using altova.M5X6SH23V6Q9
You can download the altova trial version here
http://www.altova.com/download-trial/
When you download you wll get the key for trial version on your mail id.
Steps:
1)

2)

3)

4)

5)

6)

7)

 

 8)

 9)

 10)

 11)

The different queries you can evaluate!
Queries

1)
xquery version “1.0”;

{
for $i in doc (“sample.xml”)//clg_tuple
where $i/ cid
{
$i/cid
}
{
$i/cname
}
{
$i/addr
}

}

2)
xquery version “1.0”;

{
for $i in doc (“sample.xml”)//clg_tuple
where $i/ cid=3
return

{
$i/cid
}
{
$i/cname
}
{
$i/addr
}

}

3)
xquery version “1.0”;

{
for $i in doc (“sample.xml”)//clg_tuple
where $i/ cid>3
return

{
$i/cid
}
{
$i/cname
}
{
$i/addr
}

}

4)
xquery version “1.0”;

{
for $i in doc (“sample.xml”)//clg_tuple
where $i/ addr=”wagholi”
return

{
$i/cid
}
{
$i/cname
}
{
$i/addr
}

}