file_get_contents 和 curl 获取json

2017-11-25  本文已影响0人  charmingcheng
<?php 
header("Content-type: text/html; charset=utf-8"); 
$url='http://www.example.com';

if( function_exists('file_get_contents')) {
    //file_get_contents()来获取json格式的数据
    $file_contents = file_get_contents($url);
} else {
    //curl来获取json格式的数据
    $ch = curl_init();
    $timeout = 5;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
}
$textInfo = json_decode($file_contents,true);
echo '<pre>';
print_r($textInfo);
echo '</pre>';
?>
上一篇下一篇

猜你喜欢

热点阅读