0

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

1
  • 1
    Why are you echoing [0]? What are you trying to achieve? Commented Apr 2, 2018 at 4:04

3 Answers 3

1

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.