需要你的帮助...... 我试图创建一个代码来获取.txt文件并将所有文本内容转换为json。
这是我的示例代码:
<?php
// make your required checks
$fp = 'SampleMessage01.txt';
// get the contents of file in array
$conents_arr = file($fp, FILE_IGNORE_NEW_LINES);
foreach($conents_arr as $key=>$value)
{
$conents_arr[$key] = rtrim($value, "\r");
}
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
echo $json_contents;
?>
当我试图回复$json_contents
["Sample Material 1","tRAINING|ENDING","01/25/2018 9:37:00 AM","639176882315,639176882859","Y,Y","~"]
但当我尝试像这种方法一样使用回声$json_contents[0]
我只得到每个角色的结果。
代码
结果
希望你能帮我解决这个问题。 谢谢答案 0 :(得分:1)
这种情况正在发生,因为$json_contents
是一个字符串。它可能是json字符串,但它是字符串,因此字符串属性将在此处应用,因此当您echo $json_contents[0]
时,它会为您提供字符串的第一个字符。您可以将编码的json字符串解码为对象,如下所示:
$json = json_decode($json_contents);
echo $json[0];
或在json_encode
:
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
答案 1 :(得分:1)
正如PHP.net所说 “返回包含所提供值的JSON表示的字符串。”
当你使用$ json_contents [0]时,这将返回json字符串的第一个字符。
你可以这样做
$conents_arr[0]
或使用
将您的json字符串转换为PHP数组$json_array = json_decode($json_contents, true);
echo $json_array[0];
答案 2 :(得分:0)
json_encode()函数将数组作为输入并将其转换为json字符串。
echo $json_contents;
只打印出字符串。
如果要访问它,则必须解码 JSON字符串到数组。
//this convert array to json string
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
//this convert json string to an array.
$json_contents = json_decode($json_contents, true);
//now you can access it
echo $json_contents[0];