gpt4 book ai didi

php - 使用 file_get_contents 从 url 获取 JSON

转载 作者:行者123 更新时间:2023-12-02 04:03:28 26 4
gpt4 key购买 nike

我有一个以 JSON 格式提供一些数据的服务器。我尝试用通常的方式获取这些数据:

$res = file_get_contents($url);
$result = json_decode($res);
var_dump($result);

但是 $result 还是一个字符串。问题是来自 file_get_content 的数据在数据之前有一些字母数字字符串,在数据之后有一个零。

类似于:

215ba
{"@attributes":{"ticker":"FCA"},"info...... // here all json data
0

我已经直接从 url 检查了 json 有效性,并且格式正确,我无法理解零和 215ba 来自哪里。

显然我可以删除字符串,消除两者,但我想知道是否有更具体的解决方案而不是解决方法

PS:不幸的是我无法使用 cURL

最佳答案

关于 json_decode 文档的注释:http://php.net/manual/en/function.json-decode.php

此函数仅适用于 UTF-8 编码的字符串。

类似这样的事情可能会解决它:

$contents = file_get_contents($url);
$contents = utf8_encode($contents);
$results = json_decode($contents);

如果这不起作用,您可以使用正则表达式来检查新行。假设 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);

关于php - 使用 file_get_contents 从 url 获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40785114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com