如何使用PHP获取网页变量 [英] How to use PHP to get a webpage into a variable

查看:163
本文介绍了如何使用PHP获取网页变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从网上下载一个页面,当你使用一个简单的浏览器,如Firefox,但是当我使用file_get_contents时,服务器拒绝并回复它理解的命令,但不允许这样做下载。



那么该怎么办呢?我想我在一些脚本(在Perl)看到一个方法,通过创建一个用户代理和cookie,使服务器认为你的脚本是一个真正的网络浏览器,使你的脚本像一个真正的浏览器。

$ b $

解决方案

有没有人知道这个,怎么办?

 <?php 
//创建curl资源
$ ch = curl_init

//设置url
curl_setopt($ ch,CURLOPT_URL,example.com);

//以字符串形式返回传输
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);


//设置UA
curl_setopt($ ch,CURLOPT_USERAGENT,'My App(http://www.example.com/)');

//或者,假设是一个浏览器
// curl_setopt($ ch,CURLOPT_USERAGENT,'Mozilla / 4.0(compatible; MSIE 7.0; Windows NT 5.1)');

// $ output包含输出字符串
$ output = curl_exec($ ch);

//关闭curl资源释放系统资源
curl_close($ ch);
?>

(从 http://uk.php.net/manual/en/curl.examples-basic.php


I want to download a page from the web, it's allowed to do when you are using a simple browser like Firefox, but when I use "file_get_contents" the server refuses and replies that it understands the command but don't allow such downloads.

So what to do? I think I saw in some scripts (on Perl) a way to make your script like a real browser by creating a user agent and cookies, which makes the servers think that your script is a real web browser.

Does anyone have an idea about this, how it can be done?

解决方案

Use CURL.

<?php
        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "example.com");

        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


        // set the UA
        curl_setopt($ch, CURLOPT_USERAGENT, 'My App (http://www.example.com/)');

        // Alternatively, lie, and pretend to be a browser
        // curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');

        // $output contains the output string
        $output = curl_exec($ch);

        // close curl resource to free up system resources
        curl_close($ch);     
?>

(From http://uk.php.net/manual/en/curl.examples-basic.php)

这篇关于如何使用PHP获取网页变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆