【问题标题】:Large PHP for loop with SimpleXMLElement very slow: memory issues?带有 SimpleXMLElement 的大型 PHP for 循环非常慢:内存问题?
【发布时间】:2015-06-27 15:54:17
【问题描述】:

我目前有一些 PHP 代码,它基本上从 xml 文件中提取数据并使用 $products = new SimpleXMLElement($xmlString); 创建简单的 xml 对象,然后使用 for 循环遍历此代码,在该循环中我为每个产品设置产品详细信息XML 文档。然后保存到一个mySql数据库中。

在运行此脚本时,添加的产品的频率会降低,直到它们最终在达到最大值之前停止。我曾尝试每隔一段时间运行垃圾收集,但无济于事。以及取消设置似乎不起作用的各种变量。

部分代码如下:

<?php
$servername = "localhost";
$username = "database.database";
$password = "demwke";
$database = "databasename";
$conn = new mysqli($servername, $username, $password, $database);

$file = "large.xml";
$xmlString = file_get_contents($file);
$products = new SimpleXMLElement($xmlString);
unset($xmlString, $file);
$total = count($products->datafeed[0]);

echo 'Starting<br><br>';

for($i=0;$i<$total;$i++){
    $id = $products->datafeed->prod[$i]['id'];
etc etc
    $sql = "INSERT INTO products (id, name, uid, cat, prodName, brand, desc, link, imgurl, price, subcat) VALUES ('$id', '$store', '$storeuid', '$category', '$prodName', '$brand', '$prodDesc', '$link', '$image', '$price', '$subCategory')";
}
echo '<br>Finished';
?>

所有 php 变量都使用与 $id 类似的行定义,但为了便于阅读而删除。

关于我可以做什么/阅读以完成此任务的任何想法?只要最终完成,花费的时间对我来说并不重要。

【问题讨论】:

  • 您能否进一步解释一下“减少频率直到它们最终停止”是什么意思?也许添加一段你的 XML 结构来说明?
  • 我有另一个页面用于检查数据库中的总行数。在前 5 秒之后,它大约是 4000,然后在另外 5 秒之后,大约 2000 已经添加。然后减少到每秒 10 次左右。
  • 您的数据库在插入时很慢。您可以尝试将插入打包到事务中(例如一次 500 个),检查您的密钥空间(例如,参见 stackoverflow.com/q/16977898/367456),通过准备好的语句进行优化,更重要的是,如果 mysql 操作变慢或 XML 操作变慢,则首先进行度量。我怀疑这是mysql插入操作。还要研究 INSERT INTO 页面上的 Mysql 手册并做一些研究。
  • @AdamMoseley Metric,然后才因为一些猜测答案而在错误的地方更改代码。你提出的问题越好,你就会得到更好的答案。

标签: php xml loops mysqli simplexml


【解决方案1】:

更新:不要在 SimpleXML 中使用索引,除非你有非常少个对象。请改用foreach。:

// Before, with [index]:
for ($i=0;$i<$total;$i++) {
    $id = $products->datafeed->prod[$i]['id'];
    ...

// After, with foreach():
$i = 0;
foreach ($products->datafeed->prod as $prod) {
    $i++; // Remove if you don't actually need $i
    $id = $prod['id'];
    ...

一般情况下,...-&gt;node[$i] 会访问数组node[] 并将其全部读取到所需的索引,因此迭代节点数组不是o(N),而是o(N2 )。没有变通方法,因为无法保证当您访问项目 K 时,您刚刚访问了项目 K-1(以此类推)。 foreach 保存指针,因此在 o(N) 中工作。

出于同样的原因,使用 foreach 迭代整个数组可能是有利的,即使您真的只需要很少的已知项(除非它们很少并且非常接近数组的开头):

    $a[0] = $products->datafeed->prod[15]['id'];
    ...
    $a[35] = $products->datafeed->prod[1293]['id'];

// After, with foreach():
$want = [ 15, ... 1293 ];
$i = 0;
foreach ($products->datafeed->prod as $prod) {
    if (!in_array(++$i, $want)) {
        continue;
    }
    $a[] = $prod['id'];
}

您应该首先验证增加的延迟是由 MySQLi 还是由 XML 处理引起的。您可以从循环中删除(注释掉)SQL 查询执行,而不是其他任何内容,以验证速度(当然现在会更高...... :-))现在是否保持不变,或者显示相同的下降。

我怀疑 XML 处理是罪魁祸首,在这里:

for($i=0;$i<$total;$i++){
    $id = $products->datafeed->prod[$i]['id'];

...在这里您可以访问一个越来越远的索引到 SimpleXMLObject。这可能会遇到Schlemiel the Painter 的问题。

对您的问题“我如何让循环完成,无论何时”的直接回答是“增加内存限制和最大执行时间”。

为了提高性能,您可以在提要对象中使用不同的接口:

$i = -1;
foreach ($products->datafeed->prod as $prod) {
    $i++;
    $id = $prod['id'];
    ...
}

实验

我用这个小程序读取一个大的 XML 并迭代它的内容:

// Stage 1. Create a large XML.
$xmlString = '<?xml version="1.0" encoding="UTF-8" ?>';
$xmlString .= '<content><package>';
for ($i = 0; $i < 100000; $i++) {
    $xmlString .=  "<entry><id>{$i}</id><text>The quick brown fox did what you would expect</text></entry>";
}
$xmlString .= '</package></content>';

// Stage 2. Load the XML.
$xml    = new SimpleXMLElement($xmlString);

$tick   = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    $id = $xml->package->entry[$i]->id;
    if (0 === ($id % 5000)) {
        $t = microtime(true) - $tick;
        print date("H:i:s") . " id = {$id} at {$t}\n";
        $tick = microtime(true);
    }
}

生成 XML 后,循环解析它并打印迭代 5000 个元素需要多少时间。为了验证它确实是时间增量,还打印了日期。增量应该大约是时间戳之间的时间差。

21:22:35 id = 0 at 2.7894973754883E-5
21:22:35 id = 5000 at 0.38135695457458
21:22:38 id = 10000 at 2.9452259540558
21:22:44 id = 15000 at 5.7002019882202
21:22:52 id = 20000 at 8.0867099761963
21:23:02 id = 25000 at 10.477082967758
21:23:15 id = 30000 at 12.81209897995
21:23:30 id = 35000 at 15.120756149292

结果就是这样:处理 XML 数组越来越慢。

这与使用 foreach 的程序基本相同:

// Stage 1. Create a large XML.
$xmlString = '<?xml version="1.0" encoding="UTF-8" ?>';
$xmlString .= '<content><package>';
for ($i = 0; $i < 100000; $i++) {
    $xmlString .=  "<entry><id>{$i}</id><text>The quick brown fox did ENTRY {$i}.</text></entry>";
}
$xmlString .= '</package></content>';

// Stage 2. Load the XML.
$xml    = new SimpleXMLElement($xmlString);

$i      = 0;
$tick   = microtime(true);
foreach ($xml->package->entry as $data) {
    // $id = $xml->package->entry[$i]->id;
    $id = $data->id;
    $i++;
    if (0 === ($id % 5000)) {
        $t = microtime(true) - $tick;
        print date("H:i:s") . " id = {$id} at {$t} ({$data->text})\n";
        $tick = microtime(true);
    }
}

现在时间似乎是不变的......我说“似乎”是因为它们似乎减少了大约一万倍,而且我在获得可靠的测量结果方面有些困难。

(不,我不知道。我可能从未对大型 XML 数组使用过索引)。

21:33:42 id = 0 at 3.0994415283203E-5 (The quick brown fox did ENTRY 0.)
21:33:42 id = 5000 at 0.0065329074859619 (The quick brown fox did ENTRY 5000.)
...
21:33:42 id = 95000 at 0.0065121650695801 (The quick brown fox did ENTRY 95000.)

【讨论】:

  • 谢谢你,问题是for循环。更改为 foreach 允许我在不到一秒的时间内插入 55000。
【解决方案2】:

您可以尝试增加内存限制。如果这不是一个选项,而您只需要完成一次,我个人会将其分块并一次处理 5k 个值。

<?php
$servername = "localhost";
$username = "database.database";
$password = "demwke";
$database = "databasename";
$conn = new mysqli($servername, $username, $password, $database);

$file = "large.xml";
$xmlString = file_get_contents($file);
$products = new SimpleXMLElement($xmlString);
unset($xmlString, $file);

$total = count($products->datafeed[0]);

//get your starting value for this iteration
$start = isset($_GET['start'])?(int)$_GET['start']:0;

//determine when to stop
//process no more than 5k at a time
$step = 5000;
//where to stop, either after our step (max) or the end
$limit = min($start+$step, $total);

echo 'Starting<br><br>';

//modified loop so $i starts at our start value and stops at our $limit for this load.
for($i=$start;$i<$limit;$i++){
    $id = $products->datafeed->prod[$i]['id'];
etc etc
    $sql = "INSERT INTO products (id, name, uid, cat, prodName, brand, desc, link, imgurl, price, subcat) VALUES ('$id', '$store', '$storeuid', '$category', '$prodName', '$brand', '$prodDesc', '$link', '$image', '$price', '$subCategory')";
}

if($limit >= $total){
    echo '<br>Finished';
} else {
    echo<<<HTML
<html><head>
<meta http-equiv="refresh" content="2;URL=?start={$limit}">
</head><body>
Done processing {$start} through {$limit}. Moving on to next set in 2 seconds.
</body><html>
HTML;
}
?>

只要这不是您的用户负载(例如您网站的标准访问者),就不会有问题。

另一种选择,您是否尝试过正确准备/绑定您的查询?

【讨论】:

    【解决方案3】:

    这里有两个问题需要解决:

    内存

    目前,您正在使用 file_get_contents() 将完整文件读入内存,并使用 SimpleXML 将其解析为对象结构。这两个动作都将完整的文件加载到内存中。

    更好的解决方案是使用 XMLReader:

    $reader = new XMLReader;
    $reader->open($file);
    $dom = new DOMDocument;
    $xpath = new DOMXpath($dom);
    
    // look for the first product element
    while ($reader->read() && $reader->localName !== 'product') {
      continue;
    }
    
    // while you have an product element
    while ($reader->localName === 'product') {
      // expand product element to a DOM node
      $node = $reader->expand($dom);
      // use XPath to fetch values from the node
      var_dump(
        $xpath->evaluate('string(@category)', $node),
        $xpath->evaluate('string(name)', $node),
        $xpath->evaluate('number(price)', $node)
      );
      // move to the next product sibling
      $reader->next('product');
    }
    

    性能

    处理大量数据需要时间,以串行方式进行则更耗时。

    将脚本移动到命令行可以处理超时问题。也可以使用 `set_time_limit() 来增加限制。

    另一个选项是优化插入,收集一些记录并将它们组合成一个插入。这减少了数据库服务器上的往返/工作,但会消耗更多内存。你必须找到一个平衡点。

    INSERT INTO table 
       (field1, field2) 
    VALUES 
       (value1_1, value1_2), 
       (value2_1, value2_2), ...
    

    您甚至可以将 SQL 写入文件并使用 mysql 命令行工具插入记录。这确实很快但有安全隐患,因为您需要使用exec()。

    【讨论】:

      【解决方案4】:

      请您检查以下 2 个步骤是否对您有帮助。

      1) Increase the default PHP execution time from 30 sec to a bigger one.
         ini_set('max_execution_time', 300000);
      
      2) If fails please try to execute your code though cron job/back end.
      

      【讨论】:

        【解决方案5】:

        我之前也遇到过同样的问题。

        将您的大型 xml 文件分解为较小的文件,例如 file1、file2、file3,而不是处理它们。

        您可以使用可以打开大文件的文本编辑器来分解您的 xml。爆炸文件时不要在 php 上浪费时间。

        编辑:我找到了大型 xml 文件的答案。我认为这是为此目的的最佳答案。 Parsing Huge XML Files in PHP

        【讨论】:

        • 根据 XML 结构的复杂程度,这可能不是一个简单的修复方法,这就是为什么我建议只使用 php 来跟踪您的位置并在以后的页面加载时继续您离开的位置。
        • 你确定是 XML 文件吗?并且无需使用文本编辑器进行剪切,您可以使用像 XMLReader 这样的拉式解析器并一个接一个地处理一个主要元素 - 以防 XML 文件真的太大(从问题中给出的信息来看,XML 可能不是这里有问题)。
        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 2012-10-28
        • 1970-01-01
        • 2012-08-10
        • 2017-08-15
        • 1970-01-01
        • 2018-08-02
        • 1970-01-01
        相关资源
        最近更新 更多