Pla*_*tic 2 php json file-get-contents
我有一个以 JSON 格式提供一些数据的服务器。我尝试用通常的方式获取这些数据:
$res = file_get_contents($url);
$result = json_decode($res);
var_dump($result);
Run Code Online (Sandbox Code Playgroud)
但 $result 还是一个字符串。问题是来自 file_get_content 的数据在数据之前有一些字母数字字符串,在数据之后有一个零。
就像是:
215ba
{"@attributes":{"ticker":"FCA"},"info...... // here all json data
0
Run Code Online (Sandbox Code Playgroud)
我已经直接从 url 检查了 json 有效性,并且格式正确,我无法理解零和 215ba 来自哪里。
显然我可以去掉字符串,消除两者,但我想知道是否有更具体的解决方案而不是解决方法
PS:不幸的是我不能使用cURL
关于 json_decode 文档的注释:http ://php.net/manual/en/function.json-decode.php
This function only works with UTF-8 encoded strings.。
像这样的事情可能会解决它:
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
$results = json_decode($contents);
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,您可以使用正则表达式来检查新行。假设 json 将始终位于 1 行。
<?php
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
preg_match('/^.+[\n](.+)[\n]./', $contents, $matches);
//the json is in $matches[1]
print_r($matches);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25418 次 |
| 最近记录: |