Php HTML Dom解析5000+;项目
有没有办法有效地运行/编写下面的代码 当我运行它(通过chrome浏览器)时,它总是在第500项左右超时,并将我重定向回我的主页Php HTML Dom解析5000+;项目,php,mysql,parsing,Php,Mysql,Parsing,有没有办法有效地运行/编写下面的代码 当我运行它(通过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
<?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>";
}
}
?>
开始,移除睡眠(10)代码>将为您节省大约50000秒。您将打开5000个网页并对其进行解析。这不可能那么有效。但为了防止脚本死机,可以在for循环中使用(600),确保也有一个
编辑:您不拥有服务器。这意味着您必须将其推到客户端。事情会是这样的:
PHP:
在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>
状态
$(函数(){
"严格使用",;
var get=函数(i){
如果(i>5000){
$('#status).html('complete');
}否则{
美元({
url:window.location.href,
数据:{i:i},
成功:功能(数据){
如果(数据=='ok'){
$('#status').html('fetched'+i);
get(i+1);
}否则{
$('#status').html('获取'+i+'时出错:'+data);
}
}
});
}
};
get(0);
});
编辑2:正如其他人所提到的,这很容易受到sql注入的攻击。有关准备好的语句,请参见和。为什么睡眠()?不是在循环中运行5000个查询,而是考虑建立一个长的<代码>值()、()、()、/>代码>多插入的列表。例如,您可以一次插入100个查询,将查询数减少到50个。此外,请注意,尽管这不是传统的用户输入场景,但很容易受到SQL注入的影响!您必须转义$sqlstring
。或者使用准备好的语句。嗨,Matt,如果我没有服务器,我该怎么做?
<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>