search
HomeBackend DevelopmentPHP Tutorialphp抓取页面与代码解析 推荐_PHP

得到数据我们不能直接输出,往往需要对内容进行提取,然后再进行格式化,以更加友好的方式显现出来。
下面先简单说一下本文的主要内容:

一、 PHP抓取页面的主要方法:

1. file()函数
2. file_get_contents()函数
3. fopen()->fread()->fclose()模式
4.curl方式
5. fsockopen()函数 socket模式
6. 使用插件(如:http://sourceforge.net/projects/snoopy/)

二、PHP解析html或xml代码主要方式:

1. 正则表达式
2. PHP DOMDocument对象
3. 插件(如:PHP Simple HTML DOM Parser)

如果你对以上内容已经很了解,以下内容可以飘过......

PHP抓取页面

1. file()函数
复制代码 代码如下:
$url='http://t.qq.com';
$lines_array=file($url);
$lines_string=implode('',$lines_array);
echo htmlspecialchars($lines_string);
?>


2. file_get_contents()函数
使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini,设置 allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。
复制代码 代码如下:
$url='http://t.qq.com';
$lines_string=file_get_contents($url);
echo htmlspecialchars($lines_string);
?>


3. fopen()->fread()->fclose()模式

复制代码 代码如下:
$url='http://t.qq.com';
$handle=fopen($url,"rb");
$lines_string="";
do{
$data=fread($handle,1024);
if(strlen($data)==0){break;}
$lines_string.=$data;
}while(true);
fclose($handle);
echo htmlspecialchars($lines_string);
?>


4. curl方式
使用curl必须空间开启curl。方法:windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安装curl扩展。
复制代码 代码如下:
$url='http://t.qq.com';
$ch=curl_init();
$timeout=5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$lines_string=curl_exec($ch);
curl_close($ch);
echo htmlspecialchars($lines_string);
?>


5. fsockopen()函数 socket模式
socket模式能否正确执行,也跟服务器的设置有关系,具体可以通过phpinfo查看服务器开启了哪些通信协议,比如我的本地php socket没开启http,只能使用udp测试一下了。
复制代码 代码如下:
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr
\n";
} else {
fwrite($fp, "\n");
echo fread($fp, 26);
fclose($fp);
}
?>


6. 插件
网上应该有比较多的插件,snoopy插件是在网上搜到的,有兴趣的可以研究一下。

PHP解析xml(html)

1. 正则表达式:

复制代码 代码如下:
$url='http://t.qq.com';
$lines_string=file_get_contents($url);
eregi('

(.*)',$lines_string,$title);
echo htmlspecialchars($title[0]);
?>


2. PHP DOMDocument()对象
如果远程的html或xml存在语法错误,php在解析dom的时候会报错。

复制代码 代码如下:
$url='http://www.136web.cn';
$html=new DOMDocument();
$html->loadHTMLFile($url);
$title=$html->getElementsByTagName('title');
echo $title->item(0)->nodeValue;
?>


3. 插件
本文以PHP Simple HTML DOM Parser为例,进行简单介绍,simple_html_dom的语法类似jQuery,它让php操作dom,就像使用jQuery操作dom一样的简单。
复制代码 代码如下:
$url='http://t.qq.com';
include_once('../simplehtmldom/simple_html_dom.php');
$html=file_get_html($url);
$title=$html->find('title');
echo $title[0]->plaintext;
?>


当然中国人是富有创造性的,老外往往会在技术上领先,但中国人往往会在使用上更胜一筹,往往做出一些让老外不敢想的功能,比如php的远程抓取与分析,本来是为数据的整合提供方便。但国人很喜欢这个,于是乎大量的采集站,它们本身不创造任何有价值的内容,就是靠抓取别人的网站内容,并把它据为己有。在百度里输入“php小”关键词,suggest列表第一个就是“php小偷程序”,然后把同样的关键词放入google,哥只能笑而不语。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment