1

有没有办法有效地运行/编写下面的代码?

当我运行它(通过 chrome 浏览器)时,总是倾向于在第 500 项左右超时并将我重定向回我的主页。

<?php

include_once('config.php');
include_once('simple_html_dom.php');

for($i = 0; $i <= 5000; ++$i){

// Retrieve the DOM from a given URL
$html = file_get_html($url);

// Loop that checks through page contents and retrieves all required
foreach($html->find('div.product-details-contents') as $content) {
$detail['productid'] = $i;
$detail['title'] = $content->find('span.title', 0)->plaintext;
$detail['unit'] = $content->find('span.unit-size', 0)->plaintext;

$sqlstring = implode("','", $detail); 

$sql = "INSERT INTO `cdidlist` (`productid`, `title`, `unit`) VALUES ('$sqlstring')";

if (!mysqli_query($connect, $sql)) {
echo "Error: " . mysqli_error();
}
echo $id . " " . $detail['title'] . " Item Added SUCSESSFULLY! <br>";

    }
}
?>
4

2 回答 2

2

首先,移除sleep(10);应该可以为您节省大约 50,000 秒。

于 2013-04-18T01:23:49.553 回答
1

您正在打开 5000 个网页并对其进行解析。不能那么有效地做到这一点。但是为了防止你的脚本死机,你可以在 for 循环中使用set_time_limit (600),确保你在 php.ini中也有一个适当高的超时时间。

编辑:您不拥有服务器。这意味着您将不得不将其推到客户端。它会是这样的:

PHP:

if(isset($_REQUEST['i'])) {
   $i = (int) $_REQUEST['i']; // sanitize the input
   $error_message = false;
   /*
     load the page, parse the page and input it into the DB.
     If there is an error, save it to $error_message
   */
   if(!$error_message) {
       die(json_encode('ok')); // just die'ing is usually bad, but this is a one-off script
   } else {
       die(json_encode($error_message));
   }
}

在您的 html 中:

<p id="status">Status</p>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
  $(function () {
     'use strict';
     var get = function (i) {
         if (i > 5000) {
             $('#status).html('complete');
         } else {
            $.get({
                url: window.location.href,
                data: {i: i},
                success: function (data) {
                   if(data === 'ok'){
                      $('#status').html('fetched ' + i);
                      get(i + 1);
                   } else {
                      $('#status').html('error fetching ' + i + ': ' + data);
                   }
                }  
            });
         }
     };
     get(0);
  });
</script>

编辑 2:正如其他人所提到的,这很容易受到 sql 注入的影响。请参阅PDOPDOStatement了解准备好的语句。

于 2013-04-18T01:28:09.653 回答