PHP:无限循环和时间限制!
我有一段代码,可以通过给定 ID 来获取数据。例如,如果我为其指定 ID 1230,则代码会从网站(外部)获取 ID 为 1230 的文章数据并将其插入到数据库中。
现在的问题是我需要获取所有文章,比如说 ID 00001 到 99999 的文章。 如果执行“for”循环,则 60 秒后 PHP 内部时间限制将停止循环。 如果使用某种 header("Location: code.php?id=00001")
或 header("Location: code.php?id=".$ID)
并增加 $ID++ ,然后重定向到浏览器由于无限循环或重定向问题而阻止我的同一页面。
请帮忙!
I have a piece of code that fetches data by giving it an ID. If I give it an ID of 1230 for example, the code fetches an article data with an ID of 1230 from a web site (external) and insert it into a DB.
Now, the problem is that I need to fetch all the articles, lets say from ID 00001 to 99999.
If a do a 'for' loop, after 60 seconds the PHP internal time limit stops the loop.
If a use some kind of header("Location: code.php?id=00001")
or header("Location: code.php?id=".$ID)
and increase $ID++ and then redirect to the same page the browser stops me because of the infinite loop or redirection problem.
Please HELP!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的服务器允许,这可能是最好的解决方案:只需删除此脚本的时间限制即可。
If your server lets you, this is probably the best solution: just remove the time limit for this script.
有几种方法可以做到这一点。
最好的方法是设置一个 cron 来每 X 分钟执行一次爬虫。
在 sed 中,您需要跟踪您当前的 id。
因此,如果您设置一个函数来写入文件,您可以执行以下操作
:
打开文件(获取当前 ID)
在 id 处启动解析器 60 次
插入数据
打开文件并使用新 ID 更新它
关闭文件并退出。
这将持续几个小时或无论需要多长时间。
如果您手动执行此操作,并且每次脚本完成时坐在那里刷新,那么您可以使用会话而不是将 id 写入文件
如果您愿意覆盖服务器资源,您可以使用 set_time_limit(120) 将 60 秒延长 120 秒或您喜欢的任何内容。
Well theres several ways you can do this.
The best way to do this is to set up a cron to execute your scraper every X minutes.
This being sed you will need to keep track of what id your currently at.
so if you set up a function to write to a file you can do the following way
--
Open file (get current id)
Start Parser at the id for 60 times
Insert the data
Open the file and update it with the new id
close files and exit.
This will run over space of few hours or however long it takes.
Is if your doing this manually and your sitting there and refreshing everytime the script finishes then you can use sessions instead of writing the id to the file
If your your willing to overide your servers resources you can extend the 60 seconds using set_time_limit(120) for 120 seconds or whatever you prefer.
如果您的服务器不允许您更改脚本时间限制,只需让您的脚本检查数据库中序列中最后插入的文章并从那里开始。
另一种方法:使用 Javascript“window.location =”而不是标头进行重定向。
If your server won't let you change the script time limit, just have your script check the database for the last inserted article in your sequence and start from there.
Another approach: Use Javascript "window.location = " instead of a header to redirect.