使用PHP读取XML文件需要帮助

时间:2011-03-21 02:03:28

标签: php xml parsing

喜 我想用php阅读下面的文件。该文件的大小非常大(以GB为单位)。请帮助我,因为我对此并不了解。

这是文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Articles>
        <Article>
            <header>info about article  </header>

        <metadata>


                    <dc:title>title here</dc:title>
                    <dc:author>author 1</dc:author>
                    <dc:author>author 2</dc:author>
                    <dc:author>author 3</dc:author>
                    <dc:author>author n</dc:author>

                    <dc:subject>subject here</dc:subject>


            </metadata>
        </Article>

        <resume> resume infor </resume>
        </Articles>

3 个答案:

答案 0 :(得分:6)

如果文件很大,你可能需要使用XMLReader来避免内存不足而不是SimpleXML。

答案 1 :(得分:0)

www.w3schools.com/PHP/php_xml_simplexml.asp

尝试阅读此页面。它的帮助很大。

更新在StackOverflow.com的帖子中找到此代码段:

<?php

class SimpleDMOZParser
{
    protected $_stack = array();
    protected $_file = "";
    protected $_parser = null;

    protected $_currentId = "";
    protected $_current = "";

    public function __construct($file)
    {
        $this->_file = $file;

        $this->_parser = xml_parser_create("UTF-8");
        xml_set_object($this->_parser, $this);
        xml_set_element_handler($this->_parser, "startTag", "endTag");
    }

    public function startTag($parser, $name, $attribs)
    {
        array_push($this->_stack, $this->_current);

        if ($name == "TOPIC" && count($attribs)) {
            $this->_currentId = $attribs["R:ID"];
        }

        if ($name == "LINK" && strpos($this->_currentId, "Top/Home/Consumer_Information/Electronics/") === 0) {
            echo $attribs["R:RESOURCE"] . "\n";
        }

        $this->_current = $name;
    }

    public function endTag($parser, $name)
    {
        $this->_current = array_pop($this->_stack);
    }

    public function parse()
    {
        $fh = fopen($this->_file, "r");
        if (!$fh) {
            die("Epic fail!\n");
        }

        while (!feof($fh)) {
            $data = fread($fh, 4096);
            xml_parse($this->_parser, $data, feof($fh));
        }
    }
}

$parser = new SimpleDMOZParser("content.rdf.u8");
$parser->parse();

答案 2 :(得分:0)

良好的起点是PHP的SimpleXML