Home > other >  Valid JSON from text file
Valid JSON from text file

Time:10-13

I understand there are other similar posts about this, I am going out of my wits end here.

I have a few files with some JSON (all valid according to online validators, eg. jsonlint) - see EDIT below.

$contents = file_get_contents(DATA_PATH.'/'.$type.'.json');  
$data = json_decode($contents, true);
echo var_dump($data);

Returns NULL

If I echo $contents, I do get output.

I'm not sure what is wrong? I understand file_get_contents gets it into a string, however, how do I get it in a valid JSON? Would using fopen() be any different?

I even added the JSON to a variable but had the same outcome... I must be stupid.

Note: Most JSON I'll get will be from an API, these file-based JSONs are for testing purposes.

Thanks.

EDIT: Sample json

{
    "data": [{
            "id": 1,
            "name": "Albania",
            "alpha2code": "AL",
            "alpha3code": "ALB",
            "capital": "Tirana",
            "flag": "https://cdn.elenasport.io/flags/svg/1",
            "region": "Europe",
            "subregion": "Southern Europe",
            "timezones": [
                "UTC 01:00"
            ]
        },
        {
            "id": 3,
            "name": "Algeria",
            "alpha2code": "DZ",
            "alpha3code": "DZA",
            "capital": "Algiers",
            "flag": "https://cdn.elenasport.io/flags/svg/3",
            "region": "Africa",
            "subregion": "Northern Africa",
            "timezones": [
                "UTC 01:00"
            ]
        }]
}

CodePudding user response:

Your file might have a UTF-8 BOM which is not copied when you copy-and-paste your sample JSON to a (web based) validator. It's an invisible mark at the beginning of your file.

If you run echo bin2hex(file_get_contents(DATA_PATH.'/'.$type.'.json')) your file should begin with 7b, which is a {.

If it starts with efbbbf and then a 7b, there is a BOM. Either strip it out yourself or re-save your JSON without one using a text editor like Sublime Text which allows you to configure that.

  • Related