I'm trying to get some JSON data from a url like this:
$url = 'http://site.com/search.php?term=search term here';
$resul开发者_开发知识库t = json_decode ( file_get_contents($url) );
However the client's webhost has got the allow_url_fopen
setting disabled, hence the code above doesn't work.
What's the equivalent code of the lines above? Basically, a search term needs to be submitted via $_GET
to the url.
Like this:
$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 );
$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);
All you need is here.
http://nadeausoftware.com/articles/2007/06/php_tip_how_get_web_page_using_curl
Basically, try something like this
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;
}
have you checked it out like this.?
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;
}
Thanks.
// 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);
You should then have the file contents in $data, you'll probably want to do some error checking but you can find out how to do that at php.net.
精彩评论