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