Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

How to read XML using PHP DOM

This tutorial will demonstrate the use of DOM extension in PHP to read contents of a XML file.

On Thursday, December 29th 2005 at 02:24 PM
By Nabeel Akhtar (View Profile)
*****   (Rated 4.1 with 68 votes)
Contextual Ads
More PHP Resources
Advertisement

This tutorial is for PHP starters as well as for those who are using XML parser functions to read/write XML files. This tutorial will not go into details on XML. The focus will be more on the Document Object Model (DOM) extension.


This should not be confused with DOM XML extension, which is not packaged into PHP5 and will never be (according to php.net). DOM extension allows PHP users to use the DOM functions. The function then allow users to read, write, rename tags and do all types of crazy stuff with XML documents.



First we need a XML document to experiment with. I have created a simple XML document and named it test.xml


test.xml


<?xml version="1.0" encoding="ISO-8859-1"?>

<mynotes>

<note>

<tasks>Validate data</tasks>

<details>Validate data in SQL2005 Database with SQL manager</details>

</note>

<note>

<tasks>Download Music</tasks>

<details>Download latest music from site abc</details>

</note>

</mynotes>


This XML document stores notes on things to do. You can create one for your library, restaurant, news or book inventory. Every note in this XML
file beings with and ends with . Within the tab I have created a tab for the task name ( ) and task details (

).



Next step is to read this XML and display the results on a web page.


Create another file and call it test.php. Copy the following code into it and run it.



<?
  
// DOMElement->getElementsByTagName() -- Gets elements by tagname
  // nodeValue : The value of this node, depending on its type.
  // Load XML File. You can use loadXML if you wish to load XML data from a string

  
$objDOM = new DOMDocument();
  
$objDOM->load("test.xml"); //make sure path is correct


  
$note $objDOM->getElementsByTagName("note");
  
// for each note tag, parse the document and get values for
  // tasks and details tag.

  
foreach( $note as $value )
  {
    
$tasks $value->getElementsByTagName("tasks");
    
$task  $tasks->item(0)->nodeValue;


    
$details $value->getElementsByTagName("details");
    
$detail  $details->item(0)->nodeValue;

    echo 
"$task :: $detail <br>";
  }


?>


The output on your webpage will be something like this:

Validate data :: Validate data in SQL2005 Database with SQL manager

Download Music :: Download latest music from site abc



I have documented some of the built-in functions in the code. For more details please refer to the php manual.



This tutorial is a kick start for beginners. You can retreive data from a database and create a XML document on-the-fly with DOM functions, rename tabs in an existing XML document and validate format.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by mustafa on Thursday, June 22nd 2006 at 09:40 AM

it doesn\'t work.... Parse error: syntax error, unexpected T_OBJECT_OPERATOR in .... on line 17

by avanderw on Wednesday, March 7th 2007 at 04:30 AM

the code works on php v5 but not on lower versions by the sounds of things.

by zeb on Wednesday, March 21st 2007 at 10:00 PM

I am wondering how to get the attributes out of the elements, such as the xml version and encoding in the xml:

<?xml version="1.0" encoding="ISO-8859-1"?>

thanks

by bagyaraj on Saturday, September 1st 2007 at 05:21 AM

This is a nice example to know about basic XML.
Thanks.

by sdfg on Sunday, October 7th 2007 at 02:12 AM

sfgsgsgsg sg sdfgsfgsf

by Merli on Wednesday, November 7th 2007 at 05:20 AM

PHP XML DOM tutorial very clear and easy

by Mangal on Saturday, December 1st 2007 at 04:07 AM

I want to add one more attribute in the existing tag.

Is there a way in php

by Sonny on Wednesday, March 5th 2008 at 10:15 PM

This was awesome, it got me going right away. I actually took a huge xml file and was able to parse it with your code. Today is my first day learning xml.

by puuugfgrertt on Wednesday, June 11th 2008 at 04:57 AM

etrett teeet retert etertre retertet ter

by sapta on Friday, June 27th 2008 at 10:12 PM

not working, got no luck, same as mustafa did. syntax error, unexpected T_OBJECT_OPERATOR

by Dimple on Monday, July 21st 2008 at 03:30 AM

this is very nice Example. from above example i hv just created a file and place <a></a> between specific text , but in output no link is displayed.. how to put it??

by Dimple on Monday, July 21st 2008 at 03:31 AM

this is very nice Example. from above example i hv just created a file and place <a></a> between specific text , but in output no link is displayed.. how to put it??

by wiremesh on Thursday, September 18th 2008 at 03:52 AM

really nice. Lets try it and see :)

by rajasundar on Wednesday, September 24th 2008 at 07:35 AM

This is very simple example and nice

by abhijith on Saturday, September 27th 2008 at 09:57 PM

not working ....

gives a blank page as output.. plz help ... all though it works with SAX parser but the code to write in sax parser is too long... how to read and print from XML using dom...

by haresh on Saturday, October 18th 2008 at 07:36 AM

it'a very nice understand

by pinak on Monday, October 20th 2008 at 12:26 PM

this code is good and its working...but
when there is code like
<link rel="alternate" href ="www.example.com" />
then how to obtain the value of rel, href ???????

please do reply m eager waiting for answer

by Someone on Thursday, October 23rd 2008 at 03:04 PM

i use <a href="yourpage.php?something=alternate>

Where alternate can be any value that you want to pass to the other page.

then get the value by a
$your_variable = $_GET['something'];

THANKS for this tutorial. Needed some of the inormation here

by pinak on Friday, October 24th 2008 at 05:38 AM

This script was very helpful ...
its awesome..thanks

by vincent on Wednesday, November 19th 2008 at 04:37 PM

this tutorial got me up to speed with my coursework. was stuck now i can move on. thanks so much

by suci on Friday, November 28th 2008 at 06:38 AM

how to get the attribute values of the xml file using php...

thanks in advance

by raghu on Thursday, December 4th 2008 at 11:58 AM

it is very nice and clear example for bigginers

by Vijay on Sunday, December 28th 2008 at 05:08 AM

Excellent tutorial. Thanks!
Any reference to advanced ones with ways to get attributes in xml would be very helpful

by Martin on Tuesday, December 30th 2008 at 07:43 PM

Thanks so much!.. This worked right away!.. and saved me many hours of work!!! :o)

by saran on Thursday, January 22nd 2009 at 12:07 AM

how to read an xml file stored in mysql database, extract the contents from its multiple nodes n store it in the mysql database?????????
help me out.......

by darvidian on Thursday, January 22nd 2009 at 03:16 AM

syntax error, unexpected T_OBJECT_OPERATOR

by saran on Tuesday, January 27th 2009 at 01:15 AM

thanks a lot.........
but still i've a doubt.....
how can i retrieve the xml file if it is stored in a mysql databse????????

by saran on Wednesday, January 28th 2009 at 05:04 AM

hi........
how to check whehter an alement exists in a xml file using dom xml in php........

by saran on Wednesday, January 28th 2009 at 05:24 AM

hi........
how to check whehter an element exists in a xml file using dom xml in php........

by vinod on Wednesday, January 28th 2009 at 12:17 PM

very good tutorial. thanks.

by vinod on Wednesday, January 28th 2009 at 12:22 PM

if there is one more tag <note1> then how should i do? please

by Nick on Wednesday, February 4th 2009 at 05:37 PM

superb :-)

I'm trying to parse out the "H458232" following bit between these two tags, but it doesn't work:

<contact:id>H458232</contact:id>

Possibly because there are other <contact:> type tags, eg <contact:address> etc.

How can I select just the one I need?

Thanks

by well wisher on Monday, February 9th 2009 at 05:29 AM

great work awesome

by well wisher on Monday, February 9th 2009 at 05:29 AM

great work awesome

by Rajiv on Thursday, February 12th 2009 at 01:56 AM

how to write this xml using PHP plz help me:--

<mix backFname='C:\My Documents\DataMax News\News.MP3\_Tracks\News_2_Score.mp3'
areaStart='0.309'
areaEnd='79'
minSpace='0.5'
maxSpace='4.0'
autoRemove='fromEnd'
backVol='1'
duckVol='0.15'
duckPre='0.10'
duckPost='0.3'
encodeCmd='lame -b 128 - "C:\My Documents\DataMax News\News.MP3\News_2\News.mp3"'
>
<dir fname='C:\My Documents\DataMax News\News.MP3\Pool_2\news*.mp3' />


</mix>

by Rajiv on Thursday, February 12th 2009 at 01:56 AM

how to write this xml using PHP plz help me:--

<mix backFname='C:\My Documents\DataMax News\News.MP3\_Tracks\News_2_Score.mp3'
areaStart='0.309'
areaEnd='79'
minSpace='0.5'
maxSpace='4.0'
autoRemove='fromEnd'
backVol='1'
duckVol='0.15'
duckPre='0.10'
duckPost='0.3'
encodeCmd='lame -b 128 - "C:\My Documents\DataMax News\News.MP3\News_2\News.mp3"'
>
<dir fname='C:\My Documents\DataMax News\News.MP3\Pool_2\news*.mp3' />


</mix>

by Rajiv on Thursday, February 12th 2009 at 01:56 AM

how to write this xml using PHP plz help me:--

<mix backFname='C:\My Documents\DataMax News\News.MP3\_Tracks\News_2_Score.mp3'
areaStart='0.309'
areaEnd='79'
minSpace='0.5'
maxSpace='4.0'
autoRemove='fromEnd'
backVol='1'
duckVol='0.15'
duckPre='0.10'
duckPost='0.3'
encodeCmd='lame -b 128 - "C:\My Documents\DataMax News\News.MP3\News_2\News.mp3"'
>
<dir fname='C:\My Documents\DataMax News\News.MP3\Pool_2\news*.mp3' />


</mix>

by shree on Friday, February 27th 2009 at 10:21 AM

very good tutorial for beginners.
thanks
http://shri.com.np

by BobsWitness on Tuesday, March 10th 2009 at 08:58 AM

Rajiv, I believe this is how you make your xml doc.

$xmlDoc = new DomDocument('1.0');
$mainNode = $xmlDoc->createElement('mix');
$mainNode = $xmlDoc->appendChild($mainNode);
$mainNode->setAttribute('backFname', 'C:\My Documents\DataMax News\News.MP3\_Tracks\News_2_Score.mp3');
$mainNode->setAttribute('areaStart', '0.309');
$mainNode->setAttribute('minSpace', '0.5');
$mainNode->setAttribute('maxSpace', '4.0');
$mainNode->setAttribute('autoRemove', 'fromEnd');
$mainNode->setAttribute('backVol', '1');
$mainNode->setAttribute('duckVol', '0.15');
$mainNode->setAttribute('duckPre', '0.10');
$mainNode->setAttribute('duckPost', '0.3');
$mainNode->setAttribute('encodeCmd', 'lame -b 128 - "C:\My Documents\DataMax News\News.MP3\News_2\News.mp3"');
$innerNode = $xmlDoc->createElement('dir');
$innerNode = $mainNode->appendChild($innerNode);
$innerNode->setAttribute('fname','C:\My Documents\DataMax News\News.MP3\Pool_2\news*.mp3');
$xmlDoc->save("xmlDoc.xml");

by Viji on Thursday, March 12th 2009 at 05:38 AM

Excellent Tutorial thanks. But an error thrown for an no content. Document is empty

by Viji on Thursday, March 12th 2009 at 05:38 AM

Excellent Tutorial thanks. But an error thrown for an no content. Document is empty

by Viji on Thursday, March 12th 2009 at 05:46 AM

Error : DOMDocument::load() [function.DOMDocument-load]: Document is empty

by Mary on Saturday, March 21st 2009 at 10:45 AM

<?xml version="1.0" encoding="ISO-8859-1"?>

<mynotes>

<note>

<tasks>Validate data</tasks>

<details>Validate data in SQL2005 Database with SQL manager</details>

</note>

<note>

<tasks>Download Music</tasks>

<details>Download latest music from site abc</details>

</note>

</mynotes>

if from this xml file i want to take only the elements from the first <note></note> what i have to do.

by yathirajulu on Monday, March 30th 2009 at 01:12 AM

Here, I got easy understanding code,...

thanq very much.

by raul on Tuesday, May 19th 2009 at 02:41 AM

good one for beginners

by test on Friday, June 12th 2009 at 02:28 AM

nd ddd

by test on Friday, June 12th 2009 at 02:28 AM

nd ddd

by Solaivel on Monday, June 15th 2009 at 09:03 AM

$xmlDoc = new DomDocument('1.0');
$mainNode = $xmlDoc->createElement('mix');
$mainNode = $xmlDoc->appendChild($mainNode);
$mainNode->setAttribute('backFname', 'C:\My Documents\DataMax News\News.MP3\_Tracks\News_2_Score.mp3');
$mainNode->setAttribute('areaStart', '0.309');
$mainNode->setAttribute('minSpace', '0.5');
$mainNode->setAttribute('maxSpace', '4.0');
$mainNode->setAttribute('autoRemove', 'fromEnd');
$mainNode->setAttribute('backVol', '1');
$mainNode->setAttribute('duckVol', '0.15');
$mainNode->setAttribute('duckPre', '0.10');
$mainNode->setAttribute('duckPost', '0.3');
$mainNode->setAttribute('encodeCmd', 'lame -b 128 - "C:\My Documents\DataMax News\News.MP3\News_2\News.mp3"');
$innerNode = $xmlDoc->createElement('dir');
$innerNode = $mainNode->appendChild($innerNode);
$innerNode->setAttribute('fname','C:\My Documents\DataMax News\News.MP3\Pool_2\news*.mp3');
$xmlDoc->save("xmlDoc.xml");

by none on Saturday, June 27th 2009 at 09:23 AM

<a href="www.google.com">google</a>

by Umer on Friday, July 17th 2009 at 02:36 AM

Thanx it worked for me...

by Telazorn on Saturday, August 1st 2009 at 10:35 PM

I have a litle one for you all this worked but i have an ell. that has a name like this

<player name="the name">

how would i get the name info to display?

would love the help thank you...

by Mario on Tuesday, September 1st 2009 at 09:58 AM

Thanks for the script it works perfectly on my test server using php5 but my live server is a lower version. . . . any ideas on how i can change the script to make it work?

Thanks

Mario

by Alok on Tuesday, September 22nd 2009 at 02:11 PM

how i can read xml file and print same file in browser
please reply me fast

by Mapper99 on Friday, October 2nd 2009 at 01:45 AM

Very well written...saved me a lot of work!

Mapper
http://www.freegooglewaveinvites.com

by tahir on Saturday, October 17th 2009 at 01:51 AM

this is very usefull example for the biggnerrs

by Ron on Saturday, October 31st 2009 at 11:18 AM

Worked first time. Thanks!

by abhay on Tuesday, November 10th 2009 at 01:22 AM

I got this Error
Fatal error: Call to undefined method DOMElement::item() in D:\xampp\htdocs\pc3\SMS\citisms\tryxml.php on line 16

Help me

by abhay on Tuesday, November 10th 2009 at 01:22 AM

I got this Error
Fatal error: Call to undefined method DOMElement::item() in D:\xampp\htdocs\pc3\SMS\citisms\tryxml.php on line 16

Help me

by George on Thursday, November 26th 2009 at 09:57 AM

Thanks is works.

But i have a problem.

In my xml file i have
<event type="2" id="123456">
</event>

how to read that?

by Shridhar on Friday, February 5th 2010 at 02:49 AM

thanks man.But i m not getting how
$tasks = $value->getElementsByTagName("name");
$task = $tasks->item(0)->nodeValue; works???
please send me reply on mail

by Imran Ali on Wednesday, February 10th 2010 at 06:07 AM

Thanks,it levels the ground 4 me

by Imran Ali on Wednesday, February 10th 2010 at 06:07 AM

Thanks,it levels the ground 4 me

by sajad aziz on Friday, February 19th 2010 at 04:57 AM

i have just read it, it seems very usefull, i will let you know about my experience..

thanks for helping..

by YottaByte4Us on Friday, March 19th 2010 at 12:44 PM

It works. I had to mod it a little, but now i've added a lot of other functions. Thanks!

by simranjit singh on Tuesday, April 20th 2010 at 03:48 AM

Thank you it's really helpfull!

by YottaByte4Us on Tuesday, April 20th 2010 at 09:59 AM

Damn, this thing subscribed me to comments.. Why isn't there a button [UnSubscribe] ??? :(

by YottaByte4Us on Tuesday, April 20th 2010 at 10:00 AM

Damn, this thing subscribed me to comments.. Why isn't there a button [UnSubscribe] ??? :(

by BradyVICTORIA30 on Thursday, April 22nd 2010 at 12:33 PM

Different people in the world receive the <a href="http://lowest-rate-loans.com/topics/personal-loans">personal loans</a> from various creditors, because it's comfortable and fast.

by Manpreet on Friday, May 21st 2010 at 01:18 PM

What you say - Butter or cream? Anyways this script runs smoother than that.

by Manpreet on Friday, May 21st 2010 at 01:18 PM

What you say - Butter or cream? Anyways this script runs smoother than that.

by Steve on Tuesday, June 1st 2010 at 02:59 AM

Thanks. After trying loads of different XML parsers yours was the first that actually worked.

by xp on Wednesday, June 16th 2010 at 06:03 AM

how replace $objDOM->load("test.xml"); in php 5 where allow_url_open is disabled? thanks in advance

by Cody on Friday, June 18th 2010 at 02:56 AM

For those of you that are confused as to how to get the attr of an XML node.

Read this page:
http://www.php.net/manual/en/domelement.getattribute.php

It explains how to obtain the attr value of a DOM node.

2 seconds on Google... *Sigh*

by xp on Saturday, June 19th 2010 at 03:18 AM

2 secs?
sure, but that isn't the right solution, if none tells you to use loadXML function...

by Cody on Sunday, June 20th 2010 at 02:28 AM

xp, it's assumed knowledge.

by optimus prime on Monday, June 28th 2010 at 12:19 PM

this stuff is pretty helpful

by optimus prime on Monday, June 28th 2010 at 12:19 PM

this stuff is pretty helpful

by parvez on Tuesday, July 6th 2010 at 05:02 AM

how to edit and delete xml node in file.
pls tell me

by parvez on Tuesday, July 6th 2010 at 05:02 AM

how to edit and delete xml node in file.
pls tell me

by parvez on Tuesday, July 6th 2010 at 05:02 AM

how to edit and delete xml node in file.
pls tell me

by gopi on Friday, July 9th 2010 at 08:21 AM

Nice

by ajith on Friday, July 9th 2010 at 08:22 AM

good work


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs PHP Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources