is to use PHP programs to capture information from other websites into our own database and website.
PHP production and acquisition technology:
From the bottom socket to the high-level file operation function, there are 3 This method can be used to collect.
1. Use socket technology to collect:
Socket collection is the lowest level, it just establishes a long connection, and then we have to do it ourselves Construct the http protocol string to send the request.
For example, if you want to get the content of this page, tv.youku.com/?spm=a2hww.20023042.topNav.5~1~3!2~ A, use socket to write as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
The printed result is as follows, including the returned header information and the source code of the page:
2. Use curl_a set of functions
curl encapsulates the HTTP protocol into many functions, and directly passes the corresponding parameters. Yes, it reduces the difficulty of writing HTTP protocol strings.
Prerequisite: The curl extension must be enabled in php.ini.
1 2 3 4 5 6 7 8 |
|
The printed result is as follows, including only the source code of the page:
3. Use it directly file_get_contents (top-level)
Prerequisite: Set the url address that allows opening a network in php.ini.
1 2 3 |
|
Selection of 3 methods
The above three methods are mainly used for communication between networks. The latter two are more commonly used: If you want to collect a large amount of data in batches, use the second [CURL], which has good performance and stability.
Use the third method when sending a few requests occasionally but not frequently and intensively.
Extension: How to break the anti-leeching of pictures?
For example, the pictures on the 7060 website are protected from hotlinking: the pictures can be seen on his website, but cannot be accessed outside the site.
Principle: There is a referer item in the HTTP protocol, which represents the source address of the request. The server will determine if If this request is not from this website, it will be filtered out:
Solution: Simulate it yourself when sending HTTP Just referer:
Extension: Some data must be collected when you need to log in first. You can use the simulated trial simulation to log in. Collection under status:
a. 先用浏览登录一下,登录完,浏览器的COOKIE中就会有SESSIONID
b. 发PHP发HTTP协议时,把浏览器中的SESSIONID放到PHP的HTTP协议请求里,这样就在以登录的状态发请求。
总结:所有客户端发过来的数据都可以被模拟,所以服务器上的程序必须要必要的地方过滤客户端的数据。
什么时候用以上东西?接口开发时、采集时。
二、数据采集
例如我要采集这个url里的所有美国电影的信息,
list.youku.com/category/show/c_96_a_%E7%BE%8E%E5%9B%BD_s_1_d_1_p_3.html
则先要知道电影所在的节点的结构,我们使用firebug查看。
然后开始写代码:完整代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
测试:
打印$list;
打印$img
打印$video
最终效果:
如果需要把图片拷贝到硬盘上,则在foreach循环里加上以下代码:
1 2 3 4 5 |
|
效果如下:在当前目录下的youkuimg目录下就会有下载好的图片。
The above is the detailed content of Three ways to implement data collection in PHP. For more information, please follow other related articles on the PHP Chinese website!