php – 无法从file_get_contents中获取json_decode字符串
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 无法从file_get_contents中获取json_decode字符串,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1809字,纯文字阅读大概需要3分钟。
内容图文
![php – 无法从file_get_contents中获取json_decode字符串](/upload/InfoBanner/zyjiaocheng/707/42350f3a642646c093c223fdbbf4ea99.jpg)
我最近想从Web服务获取和解码API响应.我认为只是file_get_contents然后json_decode结果字符串应该工作.
看起来我必须处理gzipped响应和格式错误的JSON才能最终解码字符串.我怎么处理这些?
解决方法:
最近我想从Web服务获取和解码API响应,然后发现它不仅仅是file_get_contents和json_decode字符串.我必须处理gzipped响应和格式错误的JSON才能最终解码字符串.
经过几个小时的搜索,下面的两个功能刚刚结束了我的一天.
// https://stackoverflow.com/questions/8895852/uncompress-gzip-compressed-http-response
if ( ! function_exists('gzdecode')) {
/**
* Decode gz coded data
*
* http://php.net/manual/en/function.gzdecode.php
*
* Alternative: http://digitalpbk.com/php/file_get_contents-garbled-gzip-encoding-website-scraping
*
* @param string $data gzencoded data
* @return string inflated data
*/
function gzdecode($data) {
// strip header and footer and inflate
return gzinflate(substr($data, 10, -8));
}
}
/**
* Fetch the requested URL and return it as decoded json object
*
* @author string Murdani Eko
* @param string $url
*/
function get_json_decode( $url ) {
$response = file_get_contents( $url );
$response = trim( $response );
// is it a valid json string?
$jsondecoded = json_decode( $response );
if( json_last_error() == JSON_ERROR_NONE ) {
return $jsondecoded;
}
// yay..! it's a gzencoded string
if( json_last_error() == JSON_ERROR_UTF8 ) {
$response = gzdecode($response);
/* After gzdecoded, there is a chance that the response
* will have extra character after the curly brackets e.g. }}gi or }} ee
* This will cause malformed JSON, and later failed json decoding
*/
// we search-reverse the closing curly bracket position
$last_curly_pos = strrpos($response, '}');
$last_curly_pos++;
// extract the correct json format using the last curly bracket position
$good_response = substr($response, 0, $last_curly_pos);
return json_decode( $good_response );
}
}
内容总结
以上是互联网集市为您收集整理的php – 无法从file_get_contents中获取json_decode字符串全部内容,希望文章能够帮你解决php – 无法从file_get_contents中获取json_decode字符串所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。