与CURL等效的file_get_contents()?

时间:2011-07-06 10:37:37

标签: php curl

我正试图从这样的网址获取一些JSON数据:

$url = 'http://site.com/search.php?term=search term here';
$result = json_decode ( file_get_contents($url) );

但是客户端的webhost已禁用allow_url_fopen设置,因此上面的代码不起作用。

上面这些行的等效代码是什么?基本上,搜索字词需要通过$_GET提交到网址。

5 个答案:

答案 0 :(得分:6)

像这样:

$url = 'http://site.com/search.php?term=search term here';

$rCURL = curl_init();

curl_setopt($rCURL, CURLOPT_URL, $url);
curl_setopt($rCURL, CURLOPT_HEADER, 0);
curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);

$aData = curl_exec($rCURL);

curl_close($rCURL);

$result = json_decode ( $aData );

答案 1 :(得分:5)

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonData = curl_exec($ch);
if ($jsonData === false) {
    throw new Exception('Can not download URL');
}
curl_close($ch);
$result = json_decode($jsonData);

答案 2 :(得分:4)

你需要的就是这里。

http://nadeausoftware.com/articles/2007/06/php_tip_how_get_web_page_using_curl

基本上,尝试这样的事情

function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = json_decode($content);
    return $header;
}

答案 3 :(得分:1)

你有没有这样检查过。?

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

感谢。

答案 4 :(得分:1)

// create a new cURL resource
$ch = curl_init();

// set parameters
$parameters = array(
    'foo'=>'bar',
    'herp'=>'derp'
);

// add get to url
$url = 'http://example.com/index.php'
$url.= '?'.http_build_query($parameters, null, '&');

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return the content

// execute
$data = curl_exec($ch);

然后你应该在$ data中包含文件内容,你可能想要做一些错误检查,但你可以在php.net找到如何做到这一点。