How to print the array that contains the tags and the data in this xml parser?
<?php
class Simple_Parser
{
var $parser;
var $error_code;
var $error_string;
var $current_line;
var $current_column;
var $data = array();
var $datas = array();
function parse($data)
{
$this->parser = xml_parser_create('UTF-8');
xml_set_object($this->parser, $this);
xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
xml_set_element_handler($this->parser, 'tag_open', 'tag_close');
xml_set_character_data_handler($this->parser, 'cdata');
if (!xml_parse($this->parser, $data))
{
$this->data = array();
$this->dat1 = array();
$this->error_code = xml_get_error_code($this->parser);
$this->error_string = xml_error_string($this->error_code);
$this->current_line = xml_get_current_line_number($this->parser);
$this->current_column = xml_get_current_column_number($this->parser);
}
else
{
$this->data = $this->data['child'];
}
xml_parser_free($this->parser);
}
function tag_open($parser, $ta开发者_JAVA百科g, $attribs)
{
$this->data['child'][$tag][] = array('data' => '', 'attribs' => $attribs, 'child' => array());
$this->datas[] =& $this->data;
$this->data =& $this->data['child'][$tag][count($this->data['child'][$tag])-1];
echo("");
}
function cdata($parser, $cdata)
{
$this->data['data'] .= $cdata;
echo "$cdata";
}
function tag_close($parser, $tag)
{
$this->data =& $this->datas[count($this->datas)-1];
//echo "$this->datas[]";
array_pop($this->datas);
}
foreach ($this->data as $i1 => $n1)
foreach ($n1 as $i2 => $n2)
foreach ($n2 as $i3 => $n3)
printf('$data[%d][%d][%d] = %d;<br>', $i1,$i2,$i3,$n3);?>
}
$file = "BLR_HOSP-1.kml";
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}
$data = fread($fp, filesize($file));
fclose($fp);
$xml_parser = new Simple_Parser;
$xml_parser->parse($data);
?>
The foreach loop didn't work . So how do give an output of the xml file I parsed and that I have stored as an array . I want to print the tags and also the data in the tag .
Looking at the code, there looks to be a few syntactical errors. Correct the following errors first, and then let us know if the problem persists:
- The line
printf('$data[%d][%d][%d] = %d;<br>', $i1,$i2,$i3,$n3);?>
has a closing PHP tag at the end. (see the?>
.) - I'm not sure that the 'foreach' loop is correct where you've placed it. I reviewed the braces (
{
,}
) a few times to make sure I'm right. It looks like theforeach
function is not contained inside a function. It looks like it's still inside the class though, which is even worse..
My suggestion is to place the 'foreach' statement, after removing the ?> characters, after the '$xml_parser->parse($data);
' command. (Make sure to edit it so the $this
is replaced with $xml_parser
.)
I haven't reviewed the rest of your code for errors--I may edit/update this answer if what I've suggested doesn't currently fix your problem, or at least help you figure out what else is wrong. :)
精彩评论