首页 / JSON / 使用PHP从网页获取JSON数据
使用PHP从网页获取JSON数据
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用PHP从网页获取JSON数据,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2674字,纯文字阅读大概需要4分钟。
内容图文
![使用PHP从网页获取JSON数据](/upload/InfoBanner/zyjiaocheng/681/fe9a651cda004cef966f44f6bf5d22ec.jpg)
我正在尝试从here (example url)获取响应,首先,我认为我应该使用file_get_contents()
尝试此操作时,出现以下错误:
Warning: file_get_contents(https://steamcommunity.com/market/pricehistory/?country=US&currency=1&appid=730&market_hash_name=SG%20553%20|%20Damascus%20Steel%20(Factory%20New)): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
我知道这是因为它正在转换&和.我尝试了许多方法来解决这个问题,但是它们都失败了,在经过一番快速搜索之后,我得出的结论是file_get_contents()转换&和自动.
我的下一步是尝试卷曲.我首先尝试了以下代码:
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://steamcommunity.com/market/pricehistory/?country=US¤cy=1&appid=730&market_hash_name='.$hash,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
但这返回了???ÿÿ»»L作为响应.我想知道这是否与json编码有关,所以我尝试将其放入json_decode(),但没有用.
接下来,我尝试了:
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://steamcommunity.com/market/pricehistory/',
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
country => "US",
currency => 1,
appid => 730,
market_hash_name => "SG%20553%20|%20Damascus%20Steel%20(Factory%20New)"
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
但再次得到了回应??ÿÿÿÿ)»L.
此响应是什么意思,我可以解析它吗?如果没有,我应该如何正确获取此数据?此外,为什么file_get_contents()不起作用?
解决方法:
我很确定这是因为您需要某种类型的访问令牌才能访问Steam Web API.
参见this answer.
本质上,Steam返回状态为“ 400 Bad Request”的错误.但是,可以通过执行以下操作忽略此错误:
<?php
$url = "https://steamcommunity.com/market/pricehistory/?country=US¤cy=1&appid=730&market_hash_name=SG%20553%20%7C%20Damascus%20Steel%20(Factory%20New)";
$context = stream_context_create(array(
'http' => array(
'ignore_errors'=>true,
'method'=>'GET'
// for more options check http://www.php.net/manual/en/context.http.php
)
));
$response = file_get_contents($url, false, $context);
echo $response; // returns "[]"
?>
确保查看SO上的this answer.
内容总结
以上是互联网集市为您收集整理的使用PHP从网页获取JSON数据全部内容,希望文章能够帮你解决使用PHP从网页获取JSON数据所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。