获取网址内容PHP

Ami*_*ugi 20 php url curl file-get-contents

我想把一个URL的内容放在一个字符串和过程中.但是,我有一个问题.

我收到此错误:

Warning: file_get_contents(http://www.findchips.com/avail?part=74ls244) [function.file-get-contents]: failed to open stream: Redirection limit reached,
Run Code Online (Sandbox Code Playgroud)

我听说这是由于页面保护和标题,cookie和东西.我怎样才能覆盖它?

我也尝试过替代品,比如fread和fopen,但我想我只是不知道该怎么做.

有人可以帮我吗?

T.T*_*dua 34

1)本地最简单的方法

<?php
echo readfile("http://example.com/");   //needs "Allow_url_include" enable
//OR
echo include("http://example.com/");    //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb"  //needs "Allow_url_fopen" enabled
?> 
Run Code Online (Sandbox Code Playgroud)

2)更好的方式是CURL:

echo get_remote_data('http://example.com/?myPage', 'var2=something&var3=blabla' ); // GET & POST request
Run Code Online (Sandbox Code Playgroud)

这里的功能代码.它会自动处理FOLLOWLOCATION问题+远程网址会自动重新校正!(src="./imageblabla.png" --------> src="http://example.com/path/imageblabla.png")


psGNU/Linux用户可能需要php5-curl包.

  • 为什么卷曲是"更好的方式"?这些理由是绝对的还是相对的?谢谢 :) (4认同)

Rue*_*uel 11

cURL,

检查您是否通过 phpinfo();

对于代码:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    } 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
Run Code Online (Sandbox Code Playgroud)


Rom*_*man 3

尝试使用cURL代替。cURL 实现了 cookie jar,而 file_get_contents 则没有。

  • 你能给我一个如何使用 cURL 获取 url 内容的例子吗?我对 php.net 的示例有疑问 (3认同)