如何在这个xml解析器中打印包含标签和数据的数组?

时间:2011-05-11 14:18:14

标签: php xml

<?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, $tag, $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);



?>

foreach循环不起作用。那么如何给出我解析的xml文件的输出以及我作为数组存储的输出。我想打印标签以及标签中的数据。

1 个答案:

答案 0 :(得分:0)

查看代码,看起来有一些语法错误。首先纠正以下错误,然后告诉我们问题是否仍然存在:

  1. printf('$data[%d][%d][%d] = %d;<br>', $i1,$i2,$i3,$n3);?>末尾有一个结束的PHP标记。 (参见?>。)
  2. 我不确定你放置它的'foreach'循环是否正确。我几次检查了大括号({})以确保我是对的。看起来函数中包含的foreach函数。看起来它仍然在中,更糟糕的是......
  3. 我的建议是在删除?&gt;之后放置'foreach'语句。 '$xml_parser->parse($data);'命令后的字符。 (请务必对其进行编辑,以便将$this替换为$xml_parser。)

    我还没有检查其余代码是否有错误 - 如果我建议的内容目前无法解决您的问题,或者至少可以帮助您找出其他问题,我可以编辑/更新此答案。 :)