我如何使用SAX解析器

时间:2010-05-19 10:21:56

标签: php xml

这是我通过SAX解析器解析它时的结果 http://img13.imageshack.us/img13/6950/75914446.jpg 这是我需要生成显示的XML源代码:

<orders>
  <order>
    <count>37</count>
    <price>49.99</price>
    <book>
      <isbn>0130897930</isbn>
      <title>Core Web Programming Second Edition</title>
      <authors>
         <count>2</count>
        <author>Marty Hall</author>
        <author>Larry Brown</author>
      </authors>
    </book>
  </order>
  <order>
    <count>1</count>
    <price>9.95</price>
    <yacht>
      <manufacturer>Luxury Yachts, Inc.</manufacturer>
      <model>M-1</model>
      <standardFeatures oars="plastic" lifeVests="none">false</standardFeatures>
</yacht>
  </order>
  <order>
    <count>3</count>
    <price>22.22</price>
    <book>
      <isbn>B000059Z4H</isbn>
      <title>Harry Potter and the Order of the Phoenix</title>
      <authors>
         <count>1</count>
        <author>J.K. Rowling</author>
      </authors>
    </book>
  </order>

我真的不知道如何编写函数代码,但我刚刚设置了解析器

$xmlParser = xml_parser_create("UTF-8");
xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($xmlParser, 'startElement', 'endElement');
xml_set_character_data_handler($xmlParser, 'HandleCharacterData');
$fileName = 'orders.xml';
    if (!($fp = fopen($fileName, 'r'))){
        die('Cannot open the XML file: ' . $fileName);
    }
    while ($data = fread($fp, 4096)){
        $parsedOkay = xml_parse($xmlParser, $data, feof($fp));
        if (!$parsedOkay){
            print ("There was an error or the parser was finished.");
            break;
        }
    }
    xml_parser_free($xmlParser);

    function startElement($xmlParser, $name, $attribs)
    {
    }

    function endElement($parser, $name)
    {
    }

    function HandleCharacterData($parser, $data)
    {
    }

1 个答案:

答案 0 :(得分:1)

基于SimpleXML的递归方法可能是一个更简单的解决方案,例如:

  $xml = new SimpleXmlElement($data);

  function renderTree(SimpleXmlElement $xml, $depth = 0) {
    $output = str_repeat('| ', $depth);
    $output .= '+-' . $xml->getName();

    if (sizeof($xml->attributes()) > 0) {
      $attrs = '';
      foreach ($xml->attributes() as $key => $value) {
        $attrs .= $key . '=' . $value . ', ';
      }
      $output .= ' (' . trim($attrs, ', ') . ')';
    }

    $output .= ': ' . (string)$xml;
    $output .= '<br />';

    if ($xml->count() > 0) {
      foreach ($xml->children() as $child) {
        $output .= renderTree($child, $depth + 1);
      }
    }

    return $output;
  }

  echo renderTree($xml);

将在示例图像中渲染树。