抱歉,如果我的问题很愚蠢,但有些东西我没有得到。 我在 PHP 进程中使用 Guzzle 来进行 API 调用。
$response = $this->client->request('GET', 'droits_acces', [
'stream' => true,
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/x-ndjson',
]
]);
但我不明白如何解释这个回应。我找到了这个用于解释 ndjson 的库:https://github.com/sunaoka/ndjson
我的逻辑是获取响应内容,将其存储在临时文件中,然后使用库读取它。
但是当我使用 $response->getBody()->getContents() 时,我得到的响应有很多换行符。然而,在 NDJSON 中,如果我理解正确的话,换行符代表一个对象与另一个对象之间的分隔。
[编辑] 这是我使用 $response->getBody()->getContents() 时得到的响应的屏幕截图。 身体反应屏幕
我尝试使用文档中的示例使用 ndjson 库来阅读它(对象之间仅存在空格,并且它有效)。两者之间唯一的区别是空格...
当我删除“额外”换行符以获得如下所示的文件时,效果很好。
在这个例子中: $content 不工作,但 $content2 工作
public function getAccessRights()
{
$temp_file = tempnam(sys_get_temp_dir(), 'TMP_');
$temp_file_with_extension = $temp_file . '.ndjson';
rename($temp_file, $temp_file_with_extension);
$file_handle = fopen($temp_file_with_extension, 'a+');
// Content not working
$content = <<<END
{
"name": "John",
"active": true
}
{
"name": "Doe",
"active": true
}
END;
// Content Working
$content2 = <<<END
{"name": "John", "active": true}
{"name": "Doe", "active": true}
END;
fwrite($file_handle, $content);
fclose($file_handle);
$ndjson = new NDJSON($temp_file_with_extension);
$result = [];
while ($json = $ndjson->readline()) {
$result[] = $json;
}
unlink($temp_file);
dd($result);
}
也许我认为我的响应 NDJSON 无效, 我现在有点困惑。如果有人对如何进行有任何提示或建议,那将非常有帮助=D
我希望我能足够清楚地解释我的问题。 预先感谢您!
private function formatJsonString($input)
{
$input = preg_replace('~[\r\n]+~', '', $input);
$input = str_replace('}', "}\n", $input);
return $input;
}
我找到了这个解决方案,它是一个格式化响应以删除多余空格的函数。
如果有人有其他想法,我愿意接受。 =D