Talib Allauddin
Talib Allauddin

Reputation: 109

Unable to get content from JSON file in php

I'm trying to get content from a JSON file to put it in MySQL database using PHP, here is how I've been trying so far.

This is the JSON file AK.json:

[
{
    "CompanyName": "Logo Shirts Direct",
    "StreetAddress": "1001 Commerce Parkway South Dr Suite E",
    "Region": "Greenwood",
    "State": "IN",
    "PostCode": "46143",
    "Phone": "(888) 341-5646"
},
{
    "CompanyName": "L.F. GRAPHICS LLC",
    "StreetAddress": "Paterson, ",
    "Region": "Paterson",
    "State": "NJ",
    "PostCode": "07524",
    "Phone": "(973) 240-7033"
},
{
    "CompanyName": "Pacific Sportswear And Emblem Company",
    "StreetAddress": "San Diego, ",
    "Region": "Diego",
    "State": "CA",
    "PostCode": "92120",
    "Phone": "(619) 281-6688"
}
]

and in PHP:

<?php
$filename = 'AK.json';
$content = file_get_contents($filename);
print_r(json_decode($content,true));
?>

When I execute this script nothing happens, also I tried the gettype() function to get the type of the variable it returns NUll.

Upvotes: 0

Views: 86

Answers (3)

Gabscap
Gabscap

Reputation: 287

It seems like your AK.json having a BOM. You can test it with

$bom = pack("CCC", 0xef, 0xbb, 0xbf);
if (0 === strncmp($content, $bom, 3)) {
    echo "BOM detected - file is UTF-8\n";
    $str = substr($content, 3);
}

Here is how you get rid of BOM and What is BOM?


Source: PHP Snippet

Upvotes: 2

user4294557
user4294557

Reputation:

try this

<?php
$data='
[
{
    "CompanyName": "Logo Shirts Direct",
    "StreetAddress": "1001 Commerce Parkway South Dr Suite E",
    "Region": "Greenwood",
    "State": "IN",
    "PostCode": "46143",
    "Phone": "(888) 341-5646"
},
{
    "CompanyName": "L.F. GRAPHICS LLC",
    "StreetAddress": "Paterson, ",
    "Region": "Paterson",
    "State": "NJ",
    "PostCode": "07524",
    "Phone": "(973) 240-7033"
},
{
    "CompanyName": "Pacific Sportswear And Emblem Company",
    "StreetAddress": "San Diego, ",
    "Region": "Diego",
    "State": "CA",
    "PostCode": "92120",
    "Phone": "(619) 281-6688"
}
]';
echo '<pre>';
print_r(json_decode($data,true));
echo '</pre>';

if its working then your AK.json file is contain any character outside of []

Upvotes: 0

MaximeK
MaximeK

Reputation: 2061

can you do :

$filename = './AK.json';
$content = file_get_contents($filename);
if($content === false){ 
  echo 'something wrong here';
}else{
  print_r(json_decode($content,true));
}

I think the problem is the path to your ressource AK.json, be sure he is in the right place :)

Upvotes: 0

Related Questions