Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : file_get_contents with json_decode not working together

Tags:

json

php

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/

like image 611
Shachar87 Avatar asked Dec 08 '22 21:12

Shachar87


1 Answers

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.

like image 161
Dekel Avatar answered Dec 10 '22 11:12

Dekel