PHP curl使用实例,phpcurl实例
概述
本博客的前面两篇文章:curl和libcurl简介以及PHP中使用curl对PHP中curl的使用做了简单介绍,但是PHP中curl的使用却并不简单,尤其是curl的各种配置项,本篇文章会讲解几个PHP的实例,以便大家更好的理解curl。
实例:抓取页面
使用curl抓取页面相对来说比较简单,但是这里有一点需要注意的是,curl默认会将抓取的页面直接输出到浏览器。然而,我们经常遇到的情况是获取抓取的内容,对内容做一定的处理之后再进行操作。因此,这里写出两种不同的情况。
直接输出到浏览器
复制代码 代码如下:
$url="www.baidu.com";
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_exec($ch);
curl_close($ch);
?>
运行上面这段代码,我们会直接看到百度首页。
不直接输出到浏览器
如果我们不想让curl抓取的内容直接输出到浏览器,那么就需要设置curl的“CURLOPT_RETURNTRANSFER”为true,这样curl抓取的内容会作为curl_exec()函数的返回值出现。
复制代码 代码如下:
$url="www.baidu.com";
$content='';
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
/*
*根据手册来看,好像PHP5.1.3以前的版本还需要配合CURLOPT_BINARYTRANSFER一起使用,
*但是5.1.3以后的版本中,该配置项已经被废弃了。
*/
//curl_setopt($ch, CURLOPT_BINARYTRANSFER,TRUE);
$content=curl_exec($ch);
var_dump($content);
curl_close($ch);
?>
运行代码,我们可以看到页面输出了获取的网页源码。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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),

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.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment