In this tutorial, we are going to learn how PHP parses xml to so it can be viewed on a web page. For this example, we are going to place information about yours truly into a table and display it on a web page.

 

Creating the XML file
We will first start out by adding some information into our XML document. We will add my name, my rank, and my place of employment.

 

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

<DATA>

<NAME>Papp, Daniel J.</NAME>
<RANK>Specialist</RANK>
<LOCATION>C company, 10th Aviation Regiment</LOCATION>

</DATA>

 

Writing the parser
Next, we will need some PHP to parse the file so that we can extract the data into a nice, readable format...this is a script I found in Core PHP programming. I highly reccommend it.


<?
class myParser

{
var $parser;

function parse($filename)
{
//create the parser here
if(!($this->parser = xml_parser_create()))
{
print(" I could not create the parser.<br>\n");
exit();
}

//associate parser with this object
xml_set_object($this->parser, &$this);

//register handlers
xml_set_character_data_handler($this->parser, "cdataHandler");
xml_set_element_handler($this->parser, "startHandler", "endHandler");

//parse the file

if(!($fp = fopen($filename, "r")))
{
print("couldn't open info.xml!<br>\n");
xml_parser_free($this->parser);
return;
}

while($line = fread($fp, 1024))
{
xml_parse($this->parser, $line, feof($fp));
}

//destroy parser
xml_parser_free($this->parser);
}

function cdataHandler($parser, $data)
{
print($data);
}

function startHandler($parser, $name, $attributes)
{
switch($name)
{
case 'DATA':
print("<br>\n");
break;

case 'NAME':
print("<br>");
break;
case 'RANK':
print("<br>\n");
break;
default:
//ignore other tags

case 'LOCATION':
print("<br>\n");
break;
default:
//ignore other tags
}
}

function endHandler($parser, $name)
{
switch($name)
{
case 'DATA':
print("</br>\n");
break;

case 'NAME';
print("</br>\n");
break;

case 'RANK';
print("</br>\n");
break;
default:
//ignore other tags

case 'LOCATION';
print("</br>\n");
break;
default:
//ignore other tags
}
}
}

$p = new myParser;
$p->parse("info.xml");

?>

 

And here is a running result:



Papp, Daniel J.

Specialist

C company, 10th Aviation Regiment