How to parse xml in php?

When I started and learn php programming language. I have wanted to get data from xml file and read with php. I searched with Google. I got a lot of source codes. Some of codes are working in my local machine but when I upload and test it. It doesn’t work. I have found some codes are work with almost all of server. I will share it back.

Firstly, I have created example xml file as songs.xml like :


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

<currentsongs>
 <song>
 <title>Song Title One</title>
 <artist>artist name</artist>

 </song>

 <song>
 <title>Song Title Two</title>
 <artist>Sec artist name</artist>

 </song>
</currentsongs>

Then in php file :

<?php

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

 $songs = $objDOM->getElementsByTagName("song");

 foreach( $songs as $value )
 {
 $title = $value->getElementsByTagName("title");
 $song_titleĀ  = $title->item(0)->nodeValue;

 $artist = $value->getElementsByTagName("artist");
 $artist_nameĀ  = $artist->item(0)->nodeValue;

 echo "$song_title - $artist_name <br>";
 }

?>

Download Source ( size 868 B)

Leave Your Response

* Name, Email, Comment are Required

Categories