Ricky Ricky - 23 hours ago 4
JSON Question

How to remove quotations from JSON file while writing from PHP?

I currently have the following code which has an array, and outputs it into a JSON file called 'example.json'.

Below is the code that outputs to it:

$x = array(1, 2, 3); //Defining two basic arrays
$y = array(2, 4, 6);
$name = array("Joe", "John", "Johnny");
echo count($x);
$objOne = '["type": "FeatureCollection", "features": [';
file_put_contents("jsonfun.json", json_encode($objOne));
for($i = 0; $i < count($x); $i++)
{
$objTwo = '{ "type": "Feature", "geometry": {"type": "Point", "coordinates": [' . $x[$i] . ', ' . $y[$i] . ']}, "properties": {"name": ' . $name[$i] . '} }]';
file_put_contents("jsonfun.json", json_encode($objTwo), FILE_APPEND);
}
$objThree = '};';
file_put_contents("jsonfun.json", json_encode($objThree), FILE_APPEND);


Output:

"[\"type\": \"FeatureCollection\", \"features\": [""{ \"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [1, 2]}, \"properties\": {\"name\": Joe} }]""{ \"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [2, 4]}, \"properties\": {\"name\": John} }]""{ \"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": [3, 6]}, \"properties\": {\"name\": Johnny} }]""};"


As you may have seen there are a lot of slashes which I don't know where they came from... and likewise there are also several quotations where they shouldn't be;

Should look like:

"[type...


Is there any chance I could remove those, or am I doing it wrong? I have tried multiple things, such as doing
JSON_FORCE_OBJECT
or simply typing the string in different ways but nothing has worked.

Answer

The reason is that you're not encoding an array / object with json_encode, instead you're writing a string that you manually built. json_encode encodes JSON from an array, object, or collection. Not from strings.

// This is a string, and will not json_encode properly
$objOne = '["type": "FeatureCollection", "features": [';
file_put_contents("jsonfun.json", json_encode($objOne));

// This is an ARRAY, and will encode properly
$objOne = array( 'type' => 'FeatureCollection',
                 'features' => array(
                        'featureOne',
                        'featureTwo'
                 )
          );

file_put_contents("jsonfun.json", json_encode($objOne));
// Will result in contents of
// {"type":"FeatureCollection","features":["featureOne","featureTwo"]}
Comments