There are many ways to parse XML using php. Below is the code which has been tested & implemented. Just copy and paste this code to read an XML and display in a web form.
sample.xml
<COMPANY>
<username> abbas_kashani </username>
<username> abbas_kashani </username>
<username> abbas_kashani </username>
</COMPANY>
ReadXML.php
class xml_story{
var $NAME;
}
$file = "sample.xml";
function contents($parser, $data){
global $current_tag, $xml_description_key1, $counter, $story_array;
switch($current_tag){
// echo $current_tag.'^%$<br>';
case $xml_description_key1:
$story_array[$counter] = new xml_story();
$story_array[$counter]->NAME = $data;
$counter++;
break;
}
}
$xml_description_key1 = "*COMPANY*USERNAME";
$counter=0;
function startTag($parser, $data){
global $current_tag;
$current_tag .= "*$data";
}
function endTag($parser, $data){
global $current_tag;
$tag_key = strrpos($current_tag, '*');
$current_tag = substr($current_tag, 0, $tag_key);
}
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "contents");
$fp = fopen($file, "r");
$data = fread($fp, 80000);
if(!(xml_parse($xml_parser, $data, feof($fp)))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}
xml_parser_free($xml_parser);
fclose($fp);
Below code can be used to iterate through the xml data which has been parsed
for($x=0;$x<count($story_array);$x++)
{
if(strlen($story_array[$x]->NAME) != 0)
echo $story_array[$x]->NAME;
}
sample.xml
<COMPANY>
<username> abbas_kashani </username>
<username> abbas_kashani </username>
<username> abbas_kashani </username>
</COMPANY>
ReadXML.php
class xml_story{
var $NAME;
}
$file = "sample.xml";
function contents($parser, $data){
global $current_tag, $xml_description_key1, $counter, $story_array;
switch($current_tag){
// echo $current_tag.'^%$<br>';
case $xml_description_key1:
$story_array[$counter] = new xml_story();
$story_array[$counter]->NAME = $data;
$counter++;
break;
}
}
$xml_description_key1 = "*COMPANY*USERNAME";
$counter=0;
function startTag($parser, $data){
global $current_tag;
$current_tag .= "*$data";
}
function endTag($parser, $data){
global $current_tag;
$tag_key = strrpos($current_tag, '*');
$current_tag = substr($current_tag, 0, $tag_key);
}
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "contents");
$fp = fopen($file, "r");
$data = fread($fp, 80000);
if(!(xml_parse($xml_parser, $data, feof($fp)))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}
xml_parser_free($xml_parser);
fclose($fp);
Below code can be used to iterate through the xml data which has been parsed
for($x=0;$x<count($story_array);$x++)
{
if(strlen($story_array[$x]->NAME) != 0)
echo $story_array[$x]->NAME;
}
No comments:
Post a Comment