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

标签 php xml parsing

我正在尝试将 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/57631843/

相关文章:

xml - 使用 BaseX 读取多个 XML 文件

python - Microsoft Powerpoint Python 解析器

python - 无法在 python 中解析 json,但可以在 json 查看器中查看文本

php - gridview 中的 Yii2 自定义 sql 查询

php - 通过php将参数传递给python脚本

php - 即使使用准备好的语句,PDO 也不处理字段数据中的撇号

android - SimpleXML 和改造 : model for response with only root element

php - 从 composer.lock(不是 composer.json)重新安装供应商

php - 在 PHP 中插入数据库

parsing - 什么时候可以使用读取进行模棱两可的解析?