I'm trying to use the advice given in How to search through a JSON Array in PHP to lookup country names based on a country code in a .json file.
I have a file, countrycodes.js which is formatted like this:
countries = [
{code: "GB", name: "United Kingdom"},
{code: "AF", name: "Afghanistan"},
// ...
{code: "ZM", name: "Zambia"},
{code: "ZW", name: "Zimbabwe"}
];
The variable, countries has to be there because part of the application relies on this.
In PHP I've done the following:
$str = file_get_contents('countrycodes.js');
var_dump($str);
This outputs a string:
string(9642) "countries = [
{code: "GB", name: "United Kingdom"},
{code: "AF", name: "Afghanistan"},
// ...
However, when I try and json_decode it, the following gives NULL:
$str = file_get_contents('countrycodes.js');
$json = json_decode($str);
var_dump($json);
I don't know why this is because json_decode accepts a string, and this is what's given on the link I posted above? I tried removing the JavaScript variable (countries = ) but this made no difference.
Ultimately what I want to do is be able to give PHP a country code such as 'GB' and get it to return the appropriate name e.g. 'United Kingdom'. My understanding of this is the json_decode part will need to work before this is possible.
For reference, the reason countries = was being used is for populating a <select> element based on advice given here: Populating select using ajax json array
countrycodes.jsis Javascript, not JSON...truetojson_decodeisn't going to help if the input isn't valid JSON.