Riyota Miyagi
Riyota Miyagi

Reputation: 19

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.

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

["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.

Code

enter image description here

Result

enter image description here

hope you can help me on this one.. thank you

Upvotes: 0

Views: 77

Answers (3)

Md. Rezve Hasan
Md. Rezve Hasan

Reputation: 74

json_encode() function takes an array as input and convert it to json string.

echo $json_contents; just print out the string.

if you want to access it you have to decode the JSON string to array.

//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];

Upvotes: 0

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

It is happening because $json_contents is a string. 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. You can either decode the encoded json string to object like below:

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

or echo it before the json_encode:

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

Upvotes: 1

Lexo Alonzo
Lexo Alonzo

Reputation: 492

As PHP.net says "Returns a string containing the JSON representation of the supplied value."

As you are using $json_contents[0] this will return the first char of the json string.

You can do this

$conents_arr[0]

Or convert your json string to PHP array using

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

Upvotes: 1

Related Questions