php获取网页内容方法
PHP用QueryList抓取网页内容

<?php require 'QueryList.class.php'; header('Content-type:text/html;charset=utf-8'); $url = '/xishuai/p/4715000.html'; //获取文章标题和内容 $reg = array( 'title'=>array('.postTitle','text'), //获取纯文本格式的标题 'content'=>array('#cnblogs_post_body','text') //获取纯文本的文章摘要 ); $rang = '#topics'; $hj = QueryList::Query($url,$reg,$rang,'curl','utf-8');
PHP用 QueryList抓取网页内容
之前抓取网页数据都是用Java Jsoup,前几天听说用PHP抓更方便,今天就简单研究了一下,主要是用QueryList来实现. QueryList是一个基于phpQuery的通用列表采集类,是一个简单、 灵活、强大的采集工具,采集任何复杂的页面 基本上就一句话就能搞定了.
// 抓取内容的div $rang = '.post_item'; $hj = QueryList::Query($url,$reg,$rang,'curl'); echo $hj->getJSON(); ?>
---------------------------------------------------------------------------
php读取文件内容的几种方法详解

php读取⽂件内容的⼏种⽅法详解⽰例代码1: ⽤file_get_contents 以get⽅式获取内容复制代码代码如下:<?php$url='/';$html=file_get_contents($url);//print_r($http_response_header);ec($html);printhr();printarr($http_response_header);printhr();>⽰例代码2: ⽤fopen打开url, 以get⽅式获取内容复制代码代码如下:<?$fp=fopen($url,'r');printarr(stream_get_meta_data($fp));printhr();while(!feof($fp)){$result.=fgets($fp,1024);}echo"url body:$result";printhr();fclose($fp);>⽰例代码3:⽤file_get_contents函数,以post⽅式获取url复制代码代码如下:<?php$data=array('foo'=>'bar');$data=http_build_query($data);$opts=array('http'=>array('method'=>'POST','header'=>"Content-type: application/x-www-form-urlencoded\r\n"."Content-Length: ".strlen($data)."\r\n",'content'=>$data),);$context=stream_context_create($opts);$html=file_get_contents('http://localhost/e/admin/test.html',false,$context);echo$html;>⽰例代码4:⽤fsockopen函数打开url,以get⽅式获取完整的数据,包括header和body复制代码代码如下:<?functionget_url($url,$cookie=false){$url=parse_url($url);$query=$url[path]."?".$url[query];ec("Query:".$query);$fp=fsockopen($url[host],$url[port]?$url[port]:80,$errno,$errstr,30);if(!$fp){$request="GET$queryHTTP/1.1\r\n";$request.="Host:$url[host]\r\n";$request.="Connection: Close\r\n";if($cookie)$request.="Cookie:$cookie\n";$request.="\r\n";fwrite($fp,$request);while(!@feof($fp)){$result.=@fgets($fp,1024);}fclose($fp);return$result;}}//获取url的html部分,去掉headerfunctionGetUrlHTML($url,$cookie=false){$rowdata=get_url($url,$cookie);if($rowdata){$body=stristr($rowdata,"\r\n\r\n");$body=substr($body,4,strlen($body));return$body;}returnfalse;}>⽰例代码5:⽤fsockopen函数打开url,以POST⽅式获取完整的数据,包括header和body 复制代码代码如下:<?functionHTTP_Post($URL,$data,$cookie,$referrer=""){// parsing the given URL$URL_Info=parse_url($URL);// Building referrerif($referrer=="")// if not given use this script. as referrer$referrer="111";// making string from $dataforeach($dataas$key=>$value)$values[]="$key=".urlencode($value);$data_string=implode("&",$values);// Find out which port is needed - if not given use standard (=80)if(!isset($URL_Info["port"]))$URL_Info["port"]=80;// building POST-request:$request.="POST ".$URL_Info["path"]." HTTP/1.1\n";$request.="Host: ".$URL_Info["host"]."\n";$request.="Referer:$referer\n";$request.="Content-type: application/x-www-form-urlencoded\n";$request.="Content-length: ".strlen($data_string)."\n";$request.="Connection: close\n";$request.="Cookie:$cookie\n";$request.="\n";$request.=$data_string."\n";$fp=fsockopen($URL_Info["host"],$URL_Info["port"]);fputs($fp,$request);while(!feof($fp)){$result.=fgets($fp,1024);}fclose($fp);return$result;>⽰例代码6:使⽤curl库,使⽤curl库之前,你可能需要查看⼀下php.ini,查看是否已经打开了curl扩展复制代码代码如下:<?$ch = curl_init();$timeout = 5;curl_setopt ($ch, CURLOPT_URL, '/');curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);$file_contents = curl_exec($ch);curl_close($ch);echo $file_contents;>关于curl库:curl官⽅⽹站http://curl.haxx.se/curl 是使⽤URL语法的传送⽂件⼯具,⽀持FTP、FTPS、HTTP HTPPS SCP SFTP TFTP TELNET DICT FILE和LDAP。
php curl 抓取页面几种方法介绍

php curl 抓取页面几种方法介绍curl主要是抓取数据,当然我们可以用其他的方法来抓取,比如fsockopen,file_get_contents 等。
但是只能抓那些能直接访问的页面,如果要抓取有页面访问控制的页面,或者是登录以后的页面就比较困难了。
是把PHP的主页取回放到一个文件中。
例1. 使用PHP的CURL模块取回PHP主页代码如下复制代码<?php$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "http://localhost/mytest/phpinfo.php");curl_setopt($ch, CURLOPT_HEADER, false);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果把这行注释掉的话,就会直接输出 $result=curl_exec($ch);curl_close($ch);2,使用代理进行抓取为什么要使用代理进行抓取呢?以google为例吧,如果去抓google的数据,短时间内抓的很频繁的话,你就抓取不到了。
google对你的ip地址做限制这个时候,你可以换代理重新抓。
代码如下复制代码<?php$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "");curl_setopt($ch, CURLOPT_HEADER, false);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);curl_setopt($ch, CURLOPT_PROXY, 125.21.23.6:8080);//url_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:password');如果要密码的话,加上这个 $result=curl_exec($ch);curl_close($ch);?>3,post数据后,抓取数据单独说一下数据提交数据,因为用curl的时候,很多时候会有数据交互的,所以比较重要的。
php解析url并得到url中的参数及获取url参数的四种方式

php解析url并得到url中的参数及获取url参数的四种⽅式下⾯通过四种实例给⼤家介绍php url 参数获取⽅式。
在已知URL参数的情况下,我们可以根据⾃⾝情况采⽤$_GET来获取相应的参数信息($_GET['name']);那,在未知情况下如何获取到URL 上的参数信息呢?第⼀种、利⽤$_SERVER内置数组变量相对较为原始的$_SERVER['QUERY_STRING']来获取,URL的参数,通常使⽤这个变量返回的会是类似这样的数据:name=tank&sex=1如果需要包含⽂件名的话可以使⽤$_SERVER["REQUEST_URI"](返回类似:/index.php?name=tank&sex=1)第⼆种、利⽤pathinfo内置函数代码如下:<?php$test = pathinfo("http://localhost/index.php");print_r($test);/*结果如下Array([dirname] => http://localhost //url的路径[basename] => index.php //完整⽂件名[extension] => php //⽂件名后缀[filename] => index //⽂件名)*/>第三种、利⽤parse_url内置函数代码如下:<?php$test = parse_url("http://localhost/index.php?name=tank&sex=1#top");print_r($test);/*结果如下Array([scheme] => http //使⽤什么协议[host] => localhost //主机名[path] => /index.php //路径[query] => name=tank&sex=1 // 所传的参数[fragment] => top //后⾯根的锚点)*/>第四种、利⽤basename内置函数代码如下:<?php$test = basename("http://localhost/index.php?name=tank&sex=1#top");echo $test;/*结果如下index.php?name=tank&sex=1#top*/>另外,还有就是⾃⼰通过正则匹配的处理⽅式来获取需要的值了。
PHP采集静态页面并把页面css,img,js保存的方法

PHP采集静态页⾯并把页⾯css,img,js保存的⽅法本⽂实例讲述了PHP采集静态页⾯并把页⾯css,img,js保存的⽅法。
分享给⼤家供⼤家参考。
具体分析如下:这是⼀个可以获取⽹页的html代码以及css,js,font和img资源的⼩⼯具,主要⽤来快速获取模板,如果你来不及设计UI或者看到不错的模板,则可以使⽤这个⼯具来抓取⽹页和提取资源⽂件,提取的内容会按相对路径来保存资源,因此你不必担⼼资源⽂件的错误url导⼊.⾸页 index.php,代码如下:复制代码代码如下:<!DOCTYPE html><html><head><meta name="author" content="flute" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>⽹页抓取器</title><link rel="stylesheet" href="main.css" media="all" /><script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="main.js"></script></head><body><h1>Web Grabber</h1><hr /><div class="box"><h2>Url</h2><div class="form"><input type="text" id="project" value="projectname" /><input type="text" id="url" value="http://" size="60" /><button class="submit" type="button">Get</button><span id="tip"></span></div></div><div class="box"><span class="all" id="saveall">Save All</span><h2>List</h2><ul id="list"></ul></div></body></html>抓取页⾯代码 grab.php,代码如下:复制代码代码如下:<?PHP/** flute* 2014/03/31*/if(isset($_POST['url'])) {if(isset($_POST['project']) && !is_dir($_POST['project'])) mkdir($_POST['project'], 0777);echo json_encode(grab($_POST['url']));}function grab($url) {//$url = '/uploads/leaves/test.html';$data = array();$file = preg_replace('/^.*//', '', $url);if(($content = file_get_contents($url)) !== false) {if(isset($_POST['project'])) file_put_contents($_POST['project'].'/'.$file, $content);$pattern = '/<link.*?href=('|")(.*?.css)1.*?>/i';if(preg_match_all($pattern, $content, $matches)) {$data['css'] = $matches[2];}$pattern = '/<script.*?src=('|")(.*?.js)1.*?>/i';if(preg_match_all($pattern, $content, $matches)) {$data['js'] = $matches[2];}$pattern = '/<img.*?src=('|")(.*?)1.*?>/i';if(preg_match_all($pattern, $content, $matches)) {$data['img'] = $matches[2];}$pattern = '/url(('|"|s)(.*?)1)/i';if(preg_match_all($pattern, $content, $matches)) {$data['src'] = $matches[2];}}return $data;}function vardump($obj) {echo '<pre>';print_r($obj);echo '</pre>';}>保存css,js,img等资源的页⾯ save.php,代码如下:复制代码代码如下:<?PHP/** flute* 2014/03/31*/if(isset($_POST['url']) && isset($_POST['project']) && isset($_POST['domain'])) { extract($_POST);$url = preg_replace('/?.*$/', '', $url);$file = $url;$arr = explode('/', $file);$length = sizeof($arr);$filename = $arr[$length - 1];$root = $project;$dir = $root;if($domain == 'http') {$dir = $root.'/http';if(!is_dir($dir)) mkdir($dir, 0777);} else {$file = $domain.'/'.$url;for($i = 0; $i < $length -1; $i++) {if(!emptyempty($arr[$i])) {$dir .= '/'.$arr[$i];if(!is_dir($dir)) mkdir($dir, 0777);}}if(!file_exists($dir.'/'.$filename) || filesize($dir.'/'.$filename) == 0) {$content = file_get_contents($file);file_put_contents($dir.'/'.$filename, $content);}}>使⽤⽅法:1. 打开index页,输⼊项⽬名和要抓取的⽹址,⽹址必须是⽂件名结尾,如index.html;2. 点Get按钮,得到当前页⾯所有的css,js,img等资源列表;3. 点击css链接会获取css⽂件中的背景资源图⽚,附加在列表后头;4. 点击Save All即可保存列表中所有的⽂件,并按相对路径⽣成;5. 如果⽹页上有http远程⽂件,将会直接保存在http⽂件夹下;6. Get和Save有时会失败,没关系重试⼏次即可。
php获取标签内容的方法

php获取标签内容的方法方法一:使用正则表达式PHP中可以使用正则表达式来匹配HTML标签,并提取其中的内容。
具体步骤如下:1. 使用file_get_contents函数读取HTML页面的内容,并保存在一个变量中。
2. 使用正则表达式来匹配指定的标签,例如匹配标题标签可以使用正则表达式"/<title>(.*?)<\/title>/"。
3. 使用preg_match函数来进行匹配,并将结果保存在一个变量中。
如果匹配成功,该变量将包含匹配到的标签内容。
4. 最后,可以通过echo语句将标签内容输出到页面上。
下面是一个示例代码:```php$html = file_get_contents('example.html');$pattern = '/<title>(.*?)<\/title>/';preg_match($pattern, $html, $matches);$title = $matches[1];echo $title;```方法二:使用DOM解析器PHP中提供了DOM解析器,可以方便地解析HTML文档,并提取其中的标签内容。
具体步骤如下:1. 使用DOMDocument类来加载HTML页面,并创建一个DOM 对象。
2. 使用DOM对象的getElementsByTagName方法来获取指定标签的元素集合。
3. 遍历元素集合,可以通过nodeValue属性来获取标签的内容。
4. 最后,可以通过echo语句将标签内容输出到页面上。
下面是一个示例代码:```php$doc = new DOMDocument();$doc->loadHTMLFile('example.html');$titles = $doc->getElementsByTagName('title');foreach ($titles as $title) {echo $title->nodeValue;}```方法三:使用XPathXPath是一种用于在XML文档中定位节点的语言,也可以用于HTML文档的解析。
php抓取页面的几种方法

php抓取页面的几种方法在做一些天气预报或者RSS订阅的程序时,往往需要抓取非本地文件,一般情况下都是利用php模拟浏览器的访问,通过http请求访问url地址,然后得到html源代码或者xml数据,得到数据我们不能直接输出,往往需要对内容进行提取,然后再进行格式化,以更加友好的方式显现出来。
下面梳理了php抓取页面的几种方法,供大家参考借鉴。
下面简单说一下php抓取页面的几种方法及原理:一、PHP抓取页面的主要方法:1.file()函数2.file_get_contents()函数3.fopen()->fread()->fclose()模式4.curl方式5.fsockopen()函数socket模式6.使用*件(如:sourceforge/projects/snoopy/)二、PHP解析html或xml代码主要方式:1.file()函数<?php$url='t.qq';$lines_array=file($url);$lines_string=implode('',$lines_array);echohtmlspecialchars($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都不能打开远程文件。
<?php$url='t.qq';$lines_string=file_get_contents($url);echohtmlspecialchars($lines_string);3.fopen()->fread()->fclose()模式<?php$url='t.qq';$handle=fopen($url,"rb");$lines_string="";do{$data=fread($handle,1024);if(strlen($data)==0){break;}$lines_string.=$data;}while(true);fclose($handle);echohtmlspecialchars($lines_string);4.curl方式使用curl必须空间开启curl。
php采集网站数据方法及思路

php采集网站数据方法及思路如何在这庞大的互联网中获取自己的需要的信息呢?可以通过学习一下专业的技能来实现,比如,php采集,用php语言写的web程序,运行于支持php的平台上。
这样就可以达到采集的目的。
所以通常所说的php采集就是使用PHP程序,把其他网站中的信息抓取到我们自己的数据库中、网站中。
一般情况下都是利用php模拟浏览器的访问,通过http请求访问url地址,然后得到html源代码或者xml数据,得到数据后我们不能直接输出,往往需要对内容进行提取,然后再进行格式化,以更加友好的方式显现出来。
下面就简单介绍一下php采集页面的几种方法及原理:一、PHP采集页面的主要方法:file()函数file_get_contents()函数fopen()->fread()->fclose()模式curl方式fsockopen()函数socket模式使用插件(如:/projects/snoopy/)二、PHP解析html或xml代码主要方式:1、file()函数** file_get_contents()函数**使用file_get_contents和fopen必须空间开启allow_url_fopen。
方法:编辑php.ini,设置allow_url_fopen = On,allow_url_fopen关闭时fopen 和file_get_contents都不能打开远程文件。
fopen()->fread()->fclose()模式2、curl方式curl把HTTP协议都封装成了很多函数,直接传相应参数即可,降低了编写HTTP 协议字符串的难度。
使用curl必须空间开启curl。
方法:windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安装c url扩展。
php获取页面class内容的方法

一、介绍在网页开发中,经常需要通过PHP来获取页面中的某个元素的class 内容。
这在一些需要动态生成网页内容或者进行数据处理的情况下非常有用。
本文将介绍如何使用PHP来获取页面中的class内容。
二、使用DOMDocument和DOMXpath1. 需要使用PHP的DOMDocument类来加载网页内容,然后再使用DOMXpath类来查询网页中的元素。
2. 假设需要获取一个网页中id为"content"的div元素的class内容,可以通过以下代码实现:```php$doc = new DOMDocument();$doc->loadHTMLFile('网络协议xxx$xpath = new DOMXpath($doc);$div = $xpath->query('//div[id="content"]');$class = $div->item(0)->getAttribute('class');echo $class;```3. 以上代码首先创建了一个DOMDocument对象,然后使用loadHTMLFile方法加载了网页内容。
接着创建了一个DOMXpath对象,并使用query方法来查询id为"content"的div元素。
最后通过getAttribute方法获取了该元素的class内容并输出。
三、使用正则表达式除了使用DOMDocument和DOMXpath类,还可以使用正则表达式来获取页面中的class内容。
以下是一个简单的示例:```php$html = file_get_contents('网络协议xxxpreg_match('/<div id="content" class="([^"]+)">/', $html, $matches);$class = $matches[1];echo $class;```以上代码使用了file_get_contents函数来获取网页内容,然后使用preg_match函数和正则表达式来匹配id为"content"的div元素的class内容并输出。
PHPxpath提取网页数据内容代码解析

PHPxpath提取⽹页数据内容代码解析想要使⽤xpath来解析html内容, PHP⾃带两个对象DOMDocument,DOMXpath,其中初始化 loadHtml⼀般都会报很多警告,但是并不影响使⽤,⽤@屏蔽错误。
/*** 初始化DOMXpath对象** @param [type] $content ⽹页内容* @param [array] $pathinfo 匹配信息** @return void*/private function _createXpathObj($content, $patinfo){// 如果没有xpath配置项,不初始化xpathif (!$this->_existsXpathParse($patinfo)) {return;}try {$dom = new \DOMDocument();@$dom->loadHtml($content);$dom->normalize();$xpath = new \DOMXpath($dom);$this->xpathObj = $xpath;} catch (\Exception $e) {getService('logger')->warning('Parse html fail', ['content' => $content]);}}其中 $node 为 DOMElement 对象。
/*** 获取Xpath解析值** @param [type] $pat 匹配模式** @return string*/private function _getXpathField($pat){$objs = $this->xpathObj->query($pat);if ($objs->length > 0) {$node = $objs->item(0);$outerHTML = $node->ownerDocument->saveHTML($node);return trim($outerHTML);# 作为⽰例输出innerhtml//$innerHTML = '';//foreach ($node->childNodes as $childNode){// $innerHTML .= $childNode->ownerDocument->saveHTML($childNode);//}//return $innerHTML;# 作为⽰例输出⽂本不含标签//return $node->textContent; //$node->nodeValue;}return '';}⽰例<?php$dom = new DOMDocument('1.0','UTF-8');$dom->loadHTML('<html><body><div><p>p1</p><p>p2</p></div></body></html>');$node = $dom->getElementsByTagName('div')->item(0);$outerHTML = $node->ownerDocument->saveHTML($node);$innerHTML = '';foreach ($node->childNodes as $childNode){$innerHTML .= $childNode->ownerDocument->saveHTML($childNode);}echo '<h2>outerHTML: </h2>';echo htmlspecialchars($outerHTML);echo '<h2>innerHTML: </h2>';echo htmlspecialchars($innerHTML);>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
PHP抓取网页内容汇总

PHP抓取网页内容汇总/quqiufeng/blog/item/7e86fb3f40b598c67d1e7150.htmlheader("Content-type: text/html; charset=utf-8");1、$xhr = new COM("MSXML2.XMLHTTP");$xhr->open("GET","http://localhost/xxx.php?id=2",false);$xhr->send();echo $xhr->responseText2、file_get_contents实现<?php$url="/pts";echo file_get_contents( $url );?>3、fopen()实现<?if ($stream = fopen('', 'r')) {// print all the page starting at the offset 10echo stream_get_contents($stream, -1, 10);fclose($stream);}if ($stream = fopen('', 'r')) {// print the first 5 bytesecho stream_get_contents($stream, 5);fclose($stream);}?>②、使用php获取网页内容/pts/archive/2007/08/26/99188.html简单的做法:<?php$url="/pts";echo file_get_contents( $url );?>或者:<?if ($stream = fopen('', 'r')) {// print all the page starting at the offset 10echo stream_get_contents($stream, -1, 10);fclose($stream);}if ($stream = fopen('', 'r')) {// print the first 5 bytesecho stream_get_contents($stream, 5);fclose($stream);}?>③、PHP获取网站内容,保存为TXT文件源码/u1/44325/showart_348444.html<?$my_book_url='/files/article/html/4/4550/index.html';ereg("/files/article/html/[0-9]+/[0-9]+/",$my_book_url,$m yBook);$my_book_txt=$myBook[0];$file_handle = fopen($my_book_url, "r");//读取文件unlink("test.txt");while (!feof($file_handle)) { //循环到文件结束$line = fgets($file_handle); //读取一行文件$line1=ereg("href=\"[0-9]+.html",$line,$reg); //分析文件内部书的文章页面$handle = fopen("test.txt", 'a');if ($line1) {$my_book_txt_url=$reg[0]; //另外赋值,给抓取分析做准备$my_book_txt_url=str_replace("href=\"","",$my_book_txt_url);$my_book_txt_over_url="$my_book_txt$my_book_txt_url"; //转换为抓取地址echo "$my_book_txt_over_url</p>"; //显示工作状态$file_handle_txt = fopen($my_book_txt_over_url, "r"); //读取转换后的抓取地址 while (!feof($file_handle_txt)) {$line_txt = fgets($file_handle_txt);$line1=ereg("^ .+",$line_txt,$reg); //根据抓取内容标示抓取$my_over_txt=$reg[0];$my_over_txt=str_replace(" "," ",$my_over_txt); //过滤字符$my_over_txt=str_replace("<br />","",$my_over_txt);$my_over_txt=str_replace("<script.language=\"javascript\">","",$my_over_txt);$my_over_txt=str_replace(""","",$my_over_txt);if ($line1) {$handle1=fwrite($handle,"$my_over_txt\n"); //写入文件}}}}fclose($file_handle_txt);fclose($handle);fclose($file_handle); //关闭文件echo "完成</p>";?>下面是比较嚣张的方法。
php中抓取网页内容的实例详解

php中抓取⽹页内容的实例详解php中抓取⽹页内容的实例详解⽅法⼀:使⽤file_get_contents⽅法实现$url = "/c/nd/2016-10-23/doc-ifxwztru6951143.shtml";$html = file_get_contents($url);//如果出现中⽂乱码使⽤下⾯代码//$getcontent = iconv("gb2312", "utf-8",$html);echo "<textarea style='width:800px;height:600px;'>".$html."</textarea>";代码很简单,⼀看就懂,不解释了。
⽅法⼆:使⽤curl实现$url = "/c/nd/2016-10-23/doc-ifxwztru6951143.shtml";$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);$html = curl_exec($ch);curl_close($ch);echo "<textarea style='width:800px;height:600px;'>".$html."</textarea>";curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);加上这句代码,表⽰如果请求被重定向时,可以访问到最终的请求页⾯,不然请求的结果会显⽰如下内容:<head><title>Object moved</title></head><body><h1>Object Moved</h1>This object may be found <a href="some link." rel="external nofollow" >here</a>.</body>如意疑问请留⾔或者到本站社区交流讨论,感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!。
PHP获取当前页面完整URL的方法

echo 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; #http://localhost:80/PHP/XX.php?id=5
//只取路径
$url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; echo dirname($url); #http://localhost/PHP
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
//获取用户代理
echo $_SERVER['HTTP_REFERER'];
//获取完整的url
echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']; #http://localhost/PHP/XX.php?id=5
二、利用PHP实现 //获取域名或主机地址
echo $_SERVER['HTTP_HOST']; #localhost
PHP实现抓取HTTPS内容

PHP实现抓取HTTPS内容一、使用cURL最简单有效的方法是使用PHP中内置的cURL函数。
cURL就是一种向指定URL发送请求,并接收响应内容的库函数,它支持所有的认证、HTTPS、HTTPPOST、HTTPGET等等。
抓取HTTPS的代码如下所示:$ch = curl_init(;curl_setopt($ch,CURLOPT_URL,$url);curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);$output=curl_exec($ch);curl_close($ch);echo($output);二、使用fsockopen另一种实现抓取HTTPS内容的方法是使用fsockopen函数。
fsockopen函数可以建立一个Socket连接,通过它可以发送和接收服务器的数据。
但它没有最上面cURL函数简单易用,下面是一个用fsockopen发送HTTPS请求的例子:$port = 443;$errno = 0;$errstr = '';if (!$fp)echo "$errstr ($errno)<br />\n";} else$out = "GET / HTTP/1.1\r\n";$out .= "Connection: Close\r\n\r\n";fwrite($fp, $out);while (!feof($fp))echo fgets($fp, 128);}fclose($fp);三、使用StreamsPHP还提供了Streams API来抓取HTTPS内容,Streams实际上是php的一个特性,它能够封装任何类型的输入输出,比如文件、网络连接、socket等等。
php使用curl和正则表达式抓取网页数据示例

php使⽤curl和正则表达式抓取⽹页数据⽰例利⽤curl和正则表达式做的⼀个针对磨铁中⽂⽹⾮vip章节的⼩说抓取器,⽀持输⼊⼩说ID下载⼩说。
依赖项:curl可以简单的看下,⾥⾯⽤到了curl ,正则表达式,ajax等技术,适合新⼿看看。
在本地测试,必须保证联⽹并且确保php开启curl的modeSpiderTools.class.php复制代码代码如下:<?phpsession_start();//封装成类开启这些⾃动抓取⽂章#header("Refresh:30;:8080");class SpiderTools{///////////////////////////////////////////////////////////////////////////////////////////////////////////*传⼊⽂章ID 解析出⽂章标题*///////////////////////////////////////////////////////////////////////////////////////////////////////////public function getBookNameById($aid){//初始化curl$ch= curl_init();//url$url='/book/'.$aid;if(is_numeric($aid)){//正则表达式匹配$ru="/<h1\sclass=\"p-title\">\s*<a\shref=\"\/book\/\d+\">(.*)\s*<\/a>\s*<\/h1>/";}else{//<title>丧⼫爆发之全家求⽣路_第⼀章丧⼫爆发 为吾友爱乐⼉更新~_磨铁</title>$ru="/<title>(.*)<\/title>/";}//设置选项,包括URLcurl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不⾃动输出内容curl_setopt($ch, CURLOPT_HEADER, 0);//不返回头部信息curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 0);//执⾏curl$output = curl_exec($ch);//错误提⽰if(curl_exec($ch) === false){die(curl_error($ch));}// 检查是否有错误发⽣if(curl_errno($ch)){echo 'Curl error: ' . curl_error($ch);}//释放curl句柄curl_close($ch);$arr=array();preg_match_all($ru,$output,$arr);return $arr[1][0];}///////////////////////////////////////////////////////////////////////////////////////////////////////////*传⼊⽂章ID 解析⽂章内容*///////////////////////////////////////////////////////////////////////////////////////////////////////////public function getBookContextById($aid){//开始解析⽂章$ids=array();$ids=explode("_",$aid);$titleId=trim($ids[0]);$aticleId=trim($ids[1]);$ch= curl_init();$ru="/<div class=\"page-content\">[\s\S]*<pre ondragstart=\"return false\" oncopy=\"return false;\" oncut=\"return false;\" oncontextmenu=\"return false\" class=\"note\" id=\"html_content_\d*\">[\s\S]*(.*)<img src=\"\/ajax\/chapter\/$titleId\/$aticleId\" class=\"hidden\" \/><\/pre>/ui";$url='/book/'.$aid;//正则表达式匹配//设置选项,包括URLcurl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不⾃动输出内容curl_setopt($ch, CURLOPT_HEADER, 0);//不返回头部信息curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 0);//执⾏curl$output = curl_exec($ch);//错误提⽰if(curl_exec($ch) === false){die(curl_error($ch));}// 检查是否有错误发⽣if(curl_errno($ch)){echo 'Curl error: ' . curl_error($ch);}$arr=array();$arr2=array();preg_match_all($ru,$output,$arr);curl_close($ch);#var_dump($arr);$s=$arr[0][0];$s=substr($s,180);$arr2=explode("<img",$s);return trim($arr2[0]);}///////////////////////////////////////////////////////////////////////////////////////////////////////////*静态⽅法 @⽣成⼩说⽂件可以直接调⽤ *///////////////////////////////////////////////////////////////////////////////////////////////////////////public static function createBookById($id){if(!is_numeric($id)){echo "<br/>INIT BEGIN START WRITE!";$st=new self();$cons=$st->getBookContextById($id);$title=$st->getBookNameById($id);$cons=trim($cons);$t=explode(" ",$title);//构造⽬录$dir=array();$dir=explode("_",$t[0]);$wzdir=$dir[0]; //书名称作为⽬录名称$wzchapter=$dir[1]; //第⼏章//创建⽬录$wzdir2=iconv("UTF-8", "GBK", $wzdir);//⽬录编码注意这⾥保留对$wzdir字符串的引⽤,⽤来构造⽂件名,不能⽤此处,防⽌⼆次编码if(!file_exists($wzdir2)){mkdir($wzdir2); //创建⽬录}//构造⽂件名$wztitle="./".$wzdir."/"."$t[0]".".txt";//保证保存的⽂件名称不是乱码$wztitle=iconv("UTF-8", "GBK", $wztitle);$f=fopen($wztitle,"w+");fwrite($f,$cons);echo "<font color='green'>$wzdir </font>".$wzchapter."<font color='red'>写⼊成功</font>";fclose($f);}else{$ids=self::getBookIdsById($id);//这⾥服务器可能会掉线,所以最好⽤session记录循环#for($i=$_SESSION["$id"."_fid"];$i<=count($ids);$_SESSION["$id"."_fid"]++,$i++){#self::createBookById($id."_".$ids[$_SESSION["$id"."_fid"]++]);//构造id#}for($i=$_SESSION["$id"."_fid"];$i<=count($ids);$_SESSION["$id"."_fid"]++,$i++){self::createBookById($id."_".$ids[$i]);//构造id}#echo "<hr/><hr/><br/><h1>写⼊⼯作全部完成</h1>";#echo $id."_".$ids[0]."<br/>";#var_dump($ids);}}/*获取⼩说的所有ID@param $id ⽂章ID@return array;*/public static function getBookIdsById($aid){$ch= curl_init();$url='/book/'.$aid."/chapter";//注意这⾥的?可以获取最少匹配项$ru='/[\s\S]*?<li class=\"\" createdate=\"\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}\">[\s\S]*?<a href=\"\/book\/'.$aid.'_(\d*?)\"\s{1}>.*? <\/a>.*?/u';//正则表达式匹配//设置选项,包括URLcurl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不⾃动输出内容curl_setopt($ch, CURLOPT_HEADER, 0);//不返回头部信息curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 0);//执⾏curl$output = curl_exec($ch);// 检查是否有错误发⽣if(curl_errno($ch)){echo 'Curl error: ' . curl_error($ch);}//释放curl句柄curl_close($ch);$arr=array();preg_match_all($ru,$output,$arr,PREG_PATTERN_ORDER);return $arr[1];}}>getinfo.php复制代码代码如下:<?phpsession_start();require_once("SpiderTools.class.php");if($_REQUEST["bid"]){if(is_numeric($_REQUEST["bid"])){SpiderTools::createBookById(trim($_REQUEST["bid"]));}else{echo "<br/>请输⼊正确的⽂章ID<br/>";}}>index.html复制代码代码如下:<html><head><meta charset="utf-8"/></head><title>下载⼩说啦</title><body><h1>输⼊磨铁中⽂⽹你想看到的⼩说ID号就可以下载⼩说啦</h1><form method="get" action="getinfo.php"><input type="text" id="myid" name="myid" value=""/><input type="button" value="⽣成⼩说" onclick="createbook();"/></form><div id="info" style="background:black;height:500px;width:1067px;overflow:scroll;color:white"></div><!-----AJAX------><script language="javascript">var xmlHttp;function createbook(){xmlHttp=GetXmlHttpObject()if (xmlHttp==null){alert ("浏览器不⽀持ajax")return}var bookid=document.getElementById("myid").valuevar url="getinfo.php"url=url+"?bid="+bookid;url=url+"&sid="+Math.random()xmlHttp.onreadystatechange=stateChangedxmlHttp.open("GET",url,true)xmlHttp.send(null)}function stateChanged(){if(xmlHttp.readyState==1){document.getElementById("info").innerHTML="正在准备⼯作,请耐⼼点哦~^_^~<img src=\"img/1.gif\" /><br/>";}if(xmlHttp.readyState==2){document.getElementById("info").innerHTML="正在联系服务器,这可能需要⼀点时间啦^><img src=\"img/2.gif\" /><^<br/>"; }if(xmlHttp.readyState==3){document.getElementById("info").innerHTML="正在解析数据<img src=\"img/3.gif\" /><br/>";}if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){document.getElementById("info").innerHTML=xmlHttp.responseText;//xmlHttp.abort();}}function GetXmlHttpObject(){var xmlHttp=null;try{// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}catch (e){//Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}}return xmlHttp;}</script></body></html>PS:关于正则,这⾥再为⼤家推荐2款本站的正则表达式在线⼯具供⼤家参考使⽤(包括正则⽣成、匹配、验证等功能):。
php解析url并得到url中的参数及获取url参数的四种方式

php解析url并得到url中的参数及获取url参数的四种方式PHP是一种支持解析URL并获取URL参数的强大编程语言。
在处理URL参数时,我们可以使用不同的方法来获取URL中的参数。
下面将介绍如何解析URL,并使用四种不同的方式获取URL参数。
首先,我们来看一下如何解析URL。
在PHP中,我们可以使用`parse_url(`函数来解析URL并将其分割成以下组成部分:协议,主机,路径,查询字符串等。
下面是一个例子:```php$parsed_url = parse_url($url);echo "协议:" . $parsed_url['scheme'] . "<br>";echo "主机:" . $parsed_url['host'] . "<br>";echo "路径:" . $parsed_url['path'] . "<br>";echo "查询字符串:" . $parsed_url['query'] . "<br>";```以上代码将输出以下结果:```路径:/path/to/file.php查询字符串:id=123&name=John+Doe```现在我们知道了如何解析URL,接下来我们将使用四种不同的方法来获取URL参数。
1.从`$_GET`数组中获取URL参数:`$_GET`是一个全局关联数组,用于获取通过GET方法传递的URL参数。
下面是一个例子:```php$id = $_GET['id'];$name = $_GET['name'];echo "ID:" . $id . "<br>";echo "姓名:" . $name . "<br>";``````ID:123姓名:John Doe```请注意,使用`$_GET`数组获取URL参数时,需要确保参数已经设置并存在于URL中,否则可能会引发错误。
php获取页面中指定内容的类

php获取页面中指定内容的类php获取页面中的指定内容,而且以封装成类。
功能:1.获取内容中的url,email,image。
2.替换内容中的url,email,image。
url:<a href="url">xxx</a>email:***************image:<img src="image">Grep.class.php'image' => '/<img.*?src=\"(http:\/\/.+\.(jpg|jpeg|gif|bmp|png))\">/i' );private$_content = ''; // 源内容/* 設置搜尋的內容* @param String $content*/public function set($content=''){$this->_content = $content;}/* 获取指定内容* @param String $type* @param int $unique 0:all 1:unique* @return Array*/public function get($type='', $unique=0){$type = strtolower($type);if($this->_content=='' || !in_array($type, array_keys($this->_pattern))){return array();}$pattern = $this->get_pattern($type); // 获取patternpreg_match_all($pattern, $this->_content, $matches);return isset($matches[1])? ( $unique==0? $matches[1] : array_unique($matches[1]) ) : array();}/* 获取替换后的内容* @param String $type* @param String $callback* @return String*/public function replace($type='', $callback=''){$type = strtolower($type);if($this->_content=='' || !in_array($type, array_keys($this->_pattern)) || $callback==''){return$this->_content;}$pattern = $this->get_pattern($type);return preg_replace_callback($pattern, $callback, $this->_content);}演示示例:。
使用phpQuery采集网页的方法

使⽤phpQuery采集⽹页的⽅法phpQuery是⼀个基于PHP的服务端开源项⽬,它可以让PHP开发⼈员轻松处理DOM⽂档内容,⽐如获取某新闻⽹站的头条信息。
更有意思的是,它采⽤了jQuery的思想,你可以像使⽤jQuery⼀样处理页⾯内容,获取你想要的页⾯信息。
采集头条先看⼀实例,现在我要采集新浪⽹国内新闻的头条,代码如下:复制代码代码如下:include 'phpQuery/phpQuery.php';phpQuery::newDocumentFile('https://');echo pq(".blkTop h1:eq(0)")->html();简单的三⾏代码,就可以获取头条内容。
⾸先在程序中包含phpQuery.php核⼼程序,然后调⽤读取⽬标⽹页,最后输出对应标签下的内容。
pq()是⼀个功能强⼤的⽅法,跟jQuery的$()如出⼀辙,jQuery的选择器基本上都能使⽤在phpQuery上,只要把“.”变成“->”。
如上例中,pq(“.blkTop h1:eq(0)”)抓取了页⾯class属性为blkTop的DIV元素,并找到该DIV内部的第⼀个h1标签,然后⽤html()⽅法获取h1标签⾥的内容(带html标签),也就是我们要获取的头条信息,如果使⽤text()⽅法,则只获取头条的⽂本内容。
当然要使⽤好phpQuery,关键是要找对⽂档中对应内容的节点。
采集⽂章列表下⾯再来看⼀个例⼦,获取⽹站的blog列表,请看代码:复制代码代码如下:include 'phpQuery/phpQuery.php';phpQuery::newDocumentFile('https://');$artlist = pq(".blog_li");foreach($artlist as $li){echo pq($li)->find('h2')->html()."";}通过循环列表中的DIV,找出⽂章标题并输出,就是这么简单。
PHP获取微信页面的指定内容

PHP获取微信页⾯的指定内容在刚⼊⼿PHP的时候,经理让我⾃⼰做⼀个⽂章的管理系统为了⽅便管理微信端发的消息。
除了简单的添加分类、管理分类、添加⽂章、管理⽂章,还有⼀个功能就是要从微信⽂章⽹址中拿到⽹址上的标题、作者以及发表时间。
⼀、页⾯使⽤ajax把微信页⾯的地址放在⽂章链接⾥,点击获取,调⽤ajax。
不说了,直接上代码<td>⽂章链接:</td><td><input type="text" id="url" name="url" size="50"> <input type="button" value="获取" onclick="javascript:return getMsg()"/></td>function getMsg(){var title=document.getElementById("title");var url=document.getElementById("url").value;var typeId;var writer=document.getElementById("writer");var addtime=document.getElementById("addtime");//alert(url);die;$.ajax({url: '/addarticle/getmsg',type: 'POST',dataType:'text',data: 'url='+url,success: function(data){var str=data;var arr=new Array();//0是标题;1是时间;2是作者var result=str.split("<<>>");for(var i=0;i<result.length;i++){arr.push(result[i]);}title.value=arr[0];addtime.value=arr[1];writer.value=arr[2];//alert(arr[0]);},error: function(){alert('请求错误');}});}⼆、在php页⾯利⽤file_get_content函数获取页⾯全部信息该函数是将页⾯中的所有内容写在字符串中,想要拿到指定的内容,就⽤到了正则匹配。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.file_get_contents获取网页内容
<?php
$url = "";
$contents = file_get_contents($url);
//如果出现中文乱码使用下面代码
//$getcontent = iconv("gb2312", "utf-8",$contents);
echo $contents;
?>
2.curl获取网页内容
<?php
$url = "";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
//在需要用户检测的网页里需要增加下面两行
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.":".US_PWD); $contents = curl_exec($ch);
curl_close($ch);
echo $contents;
?>
3.fopen->fread->fclose获取网页内容
<?php
$handle = fopen ("", "rb");
$contents = "";
do {
$data = fread($handle, 1024);
if (strlen($data) == 0) {
break;
}
$contents .= $data;
} while(true);
fclose ($handle);
echo $contents;
4,socket获取网页内容
<?php
function GETBySocket($URL, $port=80) {
//get host from url
preg_match('/\/\/.*\//sU',$URL,$host_array);
if(!$host_array[0]) {
$URL.='/';
preg_match('/\/\/.*\//sU',$URL,$host_array);
}
$host=substr($host_array[0],2,-1);
//connect
$fp = stream_socket_client("$host:$port", $errcode, $errstr, 1);// or die("get ". $host ." failed");
//
$header = "GET ". $URL. " HTTP/1.1\r\n";
$header .= "Accept: */*\r\n";
$header .= "Accept-Language: zh-cn\r\n";
//$header .= "HTTP_CONNECTION: Keep-Alive\r\n";
$header .= "HTTP_ACCEPT: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png, */*;q=0.5\r\n";
$header .= "HTTP_ACCEPT_CHARSET: gbk,*,utf-8\r\n";
//$header .= "Accept-Encoding: gzip, deflate\r\n";
$header .= "User-Agent: Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1;)\r\n";
$header .= "Host: ". $host ."\r\n";
//$header .= "Connection: Keep-Alive\r\n";
//$header .= "Cookie: cnzz02=2; rtime=1; ltime=1148456424859; cnzz_eid=56601755-\r\n\r\n";
$header .= "Connection: close\r\n\r\n";
stream_socket_sendto($fp, $header);
///////////////////$content=stream_socket_recvfrom($fp,1000,STREAM_PEEK);
$content=stream_get_contents($fp);
fclose($fp);
$position_header=strpos($content, "\r\n\r\n");
if (stripos(substr($content, 0 ,$position_header), 'Transfer-Encoding: chunked')) { return substr($content, strpos($content, "\r\n", $position_header +4)+2);
} else {
return substr($content, $position_header +4);
}
}
echo GETBySocket('/');
注:
1.使用file_get_contents和fopen必须空间开启allow_url_fopen。
方法:编辑php.ini,设置allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。
2.使用curl必须空间开启curl。
方法:windows下修改php.ini,将extension=php_curl.dll 前面的分号去掉,而且需要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux 下要安装curl扩展。