View RSS Feed

Beverleyh

XML to HTML - Getting XML Data into a Web Page with SimpleXML

Rating: 22 votes, 5.00 average.
XML stands for EXtensible Markup Language. It is a language designed to accurately describe and structure data, keeping it separate from any styling or visual formatting. Its aim is to separate presentation, structure, and meaning from the actual content - and it does a pretty good job of it.

Storing the data in this fuss-free way is great and many tools, software and websites output data/feeds in the XML format because it is reliable, format-free, robust, easily transferred and easily manipulated - I'll be showing you how to manipulate it below using PHP's simpleXML extension, which is ready built-in to PHP5.

First, here's an example of an XML file for IT jobs that need doing around the office. The data is stored in self-descriptive tags that you can define yourself. That's right! You're not limited to using pre-defined elements as you are with HTML - with XML, you can make up your own (except for the first line -prolog- which describes the document as XML);
Code:
<?xml version="1.0" encoding="utf-8"?>
<tasks>
    <task date-added="2015-12-09">
        <title>Laptop Won't Boot</title>
        <message>Laptop gets to welcome screen then crashes. Blue screen of death.</message>
        <name>Toni</name>
        <priority>Emergency</priority>
        <status>OVERDUE</status>
    </task>
    <task date-added="2016-01-13">
        <title>Memory Card</title>
        <message>Corrupt memory card. Card-reader won't recognise it. Can't get pictures from it.</message>
        <name>Jim</name>
        <priority>Normal</priority>
        <status>OPEN</status>
    </task>
    <task date-added="2016-01-12">
        <title>Printer Cartridge</title>
        <message>New cartridge required for Kyocera printer. Black. High yield.</message>
        <name>Toni</name>
        <priority>High</priority>
        <status>OPEN</status>
    </task>
    <task date-added="2016-01-10">
        <title>Projector Bulb Orders</title>
        <message>Only 2 projector bulbs left in stock. Please order more.</message>
        <name>Carl</name>
        <priority>Normal</priority>
        <status>CLOSED</status>
    </task>
</tasks>
The XML file must contain one root element that is the parent of all other elements (<tasks>)
Each item can then be nested within the parent (<task>)

This file is saved as 'tasks.xml'. Now begins the fun part - getting at the stored data and bending it to our will! Well, baby-steps first - let's start by simply outputting the bits we want to a web page...

Using simpleXML

First we have to load the XML file (which could also be a link to an online podcast or RSS news feed) into simpleXML;
Code:
<?php

	$tasks = simplexml_load_file('path/to/tasks.xml'); // could also be an URL

?>
The $tasks variable now stores an array of mapped tags, that can be accessed like this...

The PHP code below prints the title, status and date-added attribute of the first task to the page (remember that arrays start from 0 in PHP, so the first task will be stored as task[0]);
Code:
<?php

	$tasks = simplexml_load_file('path/to/tasks.xml'); // could also be an URL
	echo $tasks -> task[0] -> title;
	echo '<br/>';
	echo $tasks -> task[0] -> status;
	echo '<br/>';
	echo $tasks -> task[0]['date-added'];

?>
Using a number reference is fine for targetting specific items, but what if you want to print a list of all the XML items? You can use a foreach loop;
Code:
<?php

	$tasks = simplexml_load_file('path/to/tasks.xml'); // could also be an URL
	echo '<ul id="tasks">';
	foreach ($tasks as $task) { // list all items
        	echo '<li>';
		echo '<b>' . $task -> title . ': </b>' . $task -> message . ' <em><small>~ ' . $task -> name . '</small></em>';
		echo '<br/>';
		echo $task -> priority . ' | ' . $task -> status . ' (' . $tasks->task[0]['date-added'] . ')';
        	echo '</li>';
		}
	echo '</ul>';

?>
You can also limit the number of items displayed by using a for loop - this example displays only 3 items;
Code:
<?php

	$tasks = simplexml_load_file('path/to/tasks.xml'); // could also be an URL
	echo '<ul id="tasks">';
	for ($i = 0; $i < 3; $i++) { // list upto 3 items
        	echo '<li>';
		echo '<b>' . $tasks -> task[$i] -> title . ': </b>' . $tasks -> task[$i] -> message . ' <em><small>~ ' . $tasks -> task[$i] -> name . '</small></em>';
		echo '<br/>';
		echo $tasks -> task[$i] -> priority . ' | ' . $tasks -> task[$i] -> status . ' (' . $tasks->task[0]['date-added'] . ')';
        	echo '</li>';
		}
    	echo '</ul>';

?>
I hope you found this short introduction to XML, and XML manipulation with simpleXML useful.

I'll be expanding on this tutorial soon with a paginated RSS feed script.

Keep checking back!

Submit "XML to HTML - Getting XML Data into a Web Page with SimpleXML" to del.icio.us Submit "XML to HTML - Getting XML Data into a Web Page with SimpleXML" to StumbleUpon Submit "XML to HTML - Getting XML Data into a Web Page with SimpleXML" to Google Submit "XML to HTML - Getting XML Data into a Web Page with SimpleXML" to Digg

Updated 01-13-2016 at 04:05 PM by Beverleyh

Categories
Web Design issues , PHP coding

Comments

  1. Beverleyh's Avatar
    The paginated RSS feed tutorial is up: http://www.dynamicdrive.com/forums/e...ith-Pagination
  2. jscheuer1's Avatar
    OK, sorry - I'm commenting without thoroughly testing and reading this blog entry. That said, I'm assuming you are relying upon knowing the structure of the xml file/data. Right? In any case, that's always been my approach in the past. I just recently came upon xml_parse_into_struct(). This (standard I believe, or at least common) PHP function allows you to create at least two (or one if you prefer) arrays from the xml data/file. One of these can be easily mined for any text content without needing to know the tag name(s). For an example, see:

    http://www.dynamicdrive.com/forums/s...088#post318088

    For general info, see:

    http://php.net/manual/en/function.xm...nto-struct.php

    You can also get tons of other information (attributes) without needing to know any tag names. I've always thought this should be possible, just never came came across a function (PHP or otherwise) for it before.