dougu5847 2015-07-18 13:22
浏览 58
已采纳

将JSON转换为数组PHP时出错

Hello So i have this call.

$preciobitcoin = curlCall('https://www.bitstamp.net/api/ticker/');

and i can perfectly get $preciobitcoin['last'].

but this one

$preciodolar = curlCall('https://s3.amazonaws.com/dolartoday/data.json');

return as a string instead of an array

this is the code of the function which is not working this is the code of the function which is not working

function curlCall($url, $params = null, $contentType = 'application/json', $options = array()) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSLVERSION, 4);

if (!is_null($params) && !is_null($options['key']) && !is_null($options['sig'])) {
    curl_setopt($curl, CURLOPT_POST, TRUE);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: '.$contentType, 'key: '.$options['key'], 'sig: '.$options['sig']));
    //
} else if (!is_null($params) && !empty($params)) {
    curl_setopt($curl, CURLOPT_POST, TRUE);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: '.$contentType));
} else {
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: '.$contentType));
}

// Allow for custom requests
if (isset($options['custom_request']) && !empty($options['custom_request'])) {
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $options['custom_request']);
}

curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; cryptoGlance ' . CURRENT_VERSION . '; PHP/' . phpversion() . ')');

$curlExec = curl_exec($curl);
if ($curlExec === false || curl_errno($curl)) {
    $data = array();
} else {
    $data = json_decode($curlExec, true);
}

if (empty($data)) {
    // return non-jsonfied data
    return $curlExec;
}

curl_close($curl);

return $data;

}

  • 写回答

2条回答 默认 最新

  • doujiang2643 2015-07-18 13:46
    关注

    Probably is an encoding issue. Here is an example that works correctly on my localhost.

    $str = file_get_contents( 'https://s3.amazonaws.com/dolartoday/data.json' );
    var_dump( mb_detect_encoding( $str ) );
    
    $str = mb_convert_encoding( $str, "UTF-8" );
    var_dump( mb_detect_encoding( $str ) );
    
    var_dump( json_decode( $str ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口