简体   繁体   English

使用PHP将数组转换为JSON

[英]Array turn to json using php

need your help on this one... I'm trying to create a code that will get a .txt file and convert all text content to json. 需要您的帮助...我正在尝试创建一个将获取.txt文件并将所有文本内容转换为json的代码。

here's my sample code: 这是我的示例代码:

<?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;
?>

I already got the result when i tried to echo the $json_contents 当我尝试回显$json_contents时,我已经得到了结果

["Sample Material 1","tRAINING|ENDING","01/25/2018 9:37:00 AM","639176882315,639176882859","Y,Y","~"]

but when I tried to echo using like this method $json_contents[0] I only got per character result. 但是,当我尝试使用$json_contents[0]这样的方法进行回显时,只会得到每个字符的结果。

Code

在此处输入图片说明

Result 结果

在此处输入图片说明

hope you can help me on this one.. thank you 希望你能帮我这个忙..谢谢

It is happening because $json_contents is a string. 这是因为$json_contents是一个字符串。 It might be json string but it's string so string properties will apply here and hence when you echo $json_contents[0] it gives you first character of the string. 它可能是json字符串,但是它是字符串,因此字符串属性将在此处应用,因此当您echo $json_contents[0]它将为您提供字符串的第一个字符。 You can either decode the encoded json string to object like below: 您可以将编码的json字符串解码为如下所示的对象:

$json = json_decode($json_contents);
echo $json[0];

or echo it before the json_encode : 或在json_encode之前回显它:

echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);

As PHP.net says "Returns a string containing the JSON representation of the supplied value." 正如PHP.net所说:“返回包含所提供值的JSON表示形式的字符串 。”

As you are using $json_contents[0] this will return the first char of the json string. 当您使用$ json_contents [0]时,它将返回json字符串的第一个字符。

You can do this 你可以这样做

$conents_arr[0]

Or convert your json string to PHP array using 或者使用以下方式将json字符串转换为PHP数组

$json_array = json_decode($json_contents, true);
echo $json_array[0];

json_encode() function takes an array as input and convert it to json string. json_encode()函数将数组作为输入并将其转换为json字符串。

echo $json_contents; 回声$json_contents; just print out the string. 只需打印出字符串即可。

if you want to access it you have to decode the JSON string to array. 如果要访问它,则必须将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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM