5

I have an issuse after reading json file with file_get_contents.

When I run this code, its working ok:

<?php
$json='[  
  {  
    "fullName":"Shachar Ganot",
    "address":"Yad Rambam",
    "phoneNumber":"050-1231233",
    "email":"",
    "note":"",
    "role":"",
    "area":""
  },
  {  
    "fullName":"Betty Ganot",
    "address":"Modiin",
    "phoneNumber":"054-3213211",
    "email":"",
    "note":"",
    "role":"",
    "area":""
  },
  {  
    "fullName":"Someone Else",
    "address":"Somewhere",
    "phoneNumber":"123456789",
    "email":"",
    "note":"",
    "role":"",
    "area":""
  }
]';

//$json = file_get_contents('Test.txt');
$data = json_decode($json,true);
echo $data[0]['fullName'];

?>  

Result: Shachar Ganot

When I run this code, its empty:

<?php
$json = file_get_contents('Test.txt');
$data = json_decode($json,true);
echo $data[0]['fullName'];

?>  

Result: ****Empty - Nothig appears****

when I run this code, to check if file_get_contents is working:

<?php
$json = file_get_contents('Test.txt');
$data = json_decode($json,true);
echo $json;

?>  

Result:

[ { "fullName":"Shachar Ganot", "address":"Yad Rambam", "phoneNumber":"050-1231233", "email":"", "note":"", "role":"", "area":"" }, { "fullName":"Betty Ganot", "address":"Modiin", "phoneNumber":"054-3213211", "email":"", "note":"", "role":"", "area":"" }, { "fullName":"Someone Else", "address":"Somewhere", "phoneNumber":"123456789", "email":"", "note":"", "role":"", "area":"" } ]


What I'm missing??

Needless to say I did JSON Valid with https://jsonformatter.curiousconcept.com/

2 Answers 2

16

If your Test.txt is a encoded in UTF-8 (with BOM), the json_decode function will fail and return NULL.

You can fix this by fixing the content of your file, or trim the BOM from your $json string:

$json = trim(file_get_contents('Test.txt'), "\xEF\xBB\xBF");
$data = json_decode($json,true);
echo $data[0]['fullName'];

It will be much better to make sure the content of the file is correct and NOT use the trim function, unless you really have to.

You can use notepad++ for example to change the from content from UTF-8 with BOM to UTF-8 Without BOM.

Sign up to request clarification or add additional context in comments.

Comments

0

As of PHP 8.1 it is still not working.

For me it helped to write it to a ".json" file $output = fopen('test.json', 'a'); and read it from a ".json" file json_decode(file_get_contents('test.json')).

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.