php - 在 PHP 中解析巨大的 XML 文件

标签 php xml parsing large-files dmoz

我正在尝试将 DMOZ 内容/结构 XML 文件解析到 MySQL 中,但是执行此操作的所有现有脚本都非常旧并且无法正常工作。如何在 PHP 中打开一个大 (+1GB) XML 文件进行解析?

最佳答案

只有两个 php API 真正适合处理大文件。第一个是老expat api,第二个是较新的XMLreader功能。这些 api 读取连续的流,而不是将整个树加载到内存中(simplexml 和 DOM 就是这样做的)。

例如,您可能希望查看 DMOZ 目录的部分解析器:

<?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();

关于php - 在 PHP 中解析巨大的 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/911663/

相关文章:

python - 使用 python 通过标记文本搜索 XML

java xpath解析

python - Buildbot 解析 Python 单元测试结果

java.nio.charset.IllegalCharsetNameException : Windows-1252/WinLatin 1

php - 将经典(电子邮件/密码)登录与 Facebook 登录合并

php - 将配置(文本文件)转换为多维数组

php - 根据 MySQL 数据库中的值显示图像

java - 在 android studio 中单击按钮时创建线性布局可编程性

parsing - .next()方法在 `std::string::String`中找不到

php - 将记录移动到不同的表 MySQL