嗨我正在使用一個類來解析我的XML。重置XML解析器PHP
我不得不解析請求XML和響應XML,我想用同一個解析器來解析它。當我解析響應XML時,我總是收到junk after document element
錯誤。
我縮小了我的XML到<?xml version="1.0" encoding="UTF-8" ?><check></check>
,我仍然收到錯誤,所以我唯一能想到的是第二個<?xml ..?>
頭被解析爲'垃圾'。
我基本上想要做的是重置XML解析器,以便它可以作爲新文檔開始,但我不想創建新的解析器對象。這可能嗎?
編輯︰
我在我的XmlParser對象中使用下面的代碼。
<?php
class XmlComponent extends Object {
private $parser, $c, $current_tag;
public $contents;
function initialize(&$controller, $settings = array())
{
$this->controller =& $controller;
$this->parser = xml_parser_create();
xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, "tag_open", "tag_close");
xml_set_character_data_handler($this->parser, "cdata");
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
if (isset($settings['xml'])) {
$contents = $settings['xml'];
}
if (isset($settings['file'])) {
$f = fopen($settings['file'], 'r');
$contents = fread($f, filesize($settings['file']));
fclose($f);
}
debug($this->parse($contents));
}
public function parse($xml)
{
$xml = trim(preg_replace("/>\s+</", '><', $xml));
$this->contents = array();
$this->c = &$this->contents;
xml_parse($this->parser, $xml);
return xml_error_string(xml_get_error_code($this->parser))."\r\n".$xml;
}
//*/
public function xml($root)
{
$xml = '';
foreach ($root as $tag=>$elem) {
if (substr($tag, 0,1) != '@') {
foreach ($elem as $val) {
$xml .= '<'.$tag;
if (is_array($val) && isset($val['@attributes'])) {
foreach($val['@attributes'] as $a_key => $a_val) {
$xml .= ' '.$a_key.'="'.$a_val.'"';
}
}
$xml .= '>';
if (is_array($val) && isset($val['@data'])) {
$xml .= $val['@data'];
}
$xml .= $this->xml($val);
$xml .= '</'.$tag.'>';
}
}
}
return $xml;
}
//*/
private function tag_open($parser, $tag, $attributes)
{
if (!empty($attributes)) { $this->c[$tag][] = array('@attributes' => $attributes, '@parent' => &$this->c); }
else { $this->c[$tag][] = array('@parent' => &$this->c); }
$this->c =& $this->c[$tag][count($this->c[$tag]) - 1];
}
private function tag_close($parser, $tag)
{
$parent = &$this->c['@parent'];
unset($this->c['@parent']);
$this->c =& $parent;
}
private function cdata($parser, $data)
{
if (!empty($data)) {$this->c['@data'] = $data;}
}
//*/
}
?>
創建新對象有什麼問題? – deceze 2010-07-08 07:45:46
您可能想要提供更多關於您使用的解析器的信息。否則,我們應該如何知道它是否能夠滿足你的要求? – Gordon 2010-07-08 07:57:26
一些代碼會有幫助。 – 2010-07-08 07:59:23