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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With