Home » XML Parsing using PHP

XML Parsing using PHP

I had wanted to write this tutorial sometime ago but never got time to finish it. Now I have. This is a tutorial I hope will help others who have had similar problems parsing XML data using php.

I was attempting to insert data into a database from an XML file for a client but was unable to identify each tag. Identifying the tag was important so that I can tell what part of the data goes were in the database.

After much research on how to parse the information I found very little on what I needed to insert the data into the database easy. This is what I have created to achieve the parsing and can be customized to your needs.

/* Opens the file and stores it as a variable. */
function get_content($url){
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);

	ob_start();

	curl_exec($ch);
	curl_close($ch);
	$string = ob_get_contents();

	ob_end_clean();

	return $string;
}
/* Removes the beginning and end of tag content. */
function explode_tag($item, $tag){
	$p1 = strpos($item, "<".$tag.">");
	$p2 = strpos($item, "</".$tag.">");
	$clean = $p2-$p1;
	$item = substr($item, $p1, $clean);
	$item = str_replace("<".$tag.">", "", $item);
	$item = str_replace("</".$tag.">", "", $item);

	$tag = $item;

	return $tag;
}

This will fetch the content and extract the data from the tag.

$url equals the location of your XML file location.

The next piece will allow you to remove any HTML tags including links.

/* Removes any HTML Tags. */
function filter_tag($tag){
	$tag = strip_tags($tag, '');

	return $tag;
}

How to use these functions is up to you. Here is an example fetching a description from a blog rss feed.

$description = explode_tag($item, 'description'); // This fetches the description.
$description = filter_tag($description); // Use this if you want to remove any HTML content.

Now you able to insert the fetched data into a database using the new identified tag you have given with a dollar sign i.e. $description

Trackbacks/Pingbacks

  1. Tweets that mention XML Parsing using PHP | Sebs Studio -- Topsy.com - December 1, 2010

    [...] This post was mentioned on Twitter by Sebastien, Seb's Studio. Seb's Studio said: XML Parsing using PHP http://goo.gl/fb/juUXE [...]

Leave a Reply

0€0 items

Cart