A
A
Aidar2018-05-06 16:25:57
PHP
Aidar, 2018-05-06 16:25:57

How to properly generate json file?

Hello! For example, there is such json content

{    
    "features": [{
         "type": "Feature", 
         "geometry": {
             "type": "Point", 
             "coordinates": [55.831903, 37.411961]
            }
        }       
    ]
}

All this is generated like this
$json = json_decode(file_get_contents('data.json'), true);
$json['features'][] = [
      'type' => 'Feature',
      'geometry' => [
            'type' => 'Point',
            'coordinates' => [55.831903,37.411961]
        ],        
];
file_put_contents('data.json', json_encode($json));

Everything works well. Those. when changing the coordinates and running the code above, a new array with data is added and looks like this
{    
    "features": [
       {
         "type": "Feature", 
         "geometry": {
             "type": "Point", 
             "coordinates": [55.831903, 37.411961]
            }
        },
        {
         "type": "Feature", 
         "geometry": {
             "type": "Point", 
             "coordinates": [65.831903, 47.411961]
            }
        }             
    ]
}

Here it was necessary to add "type": "FeatureCollection" before "features", but I don't know how. To end up looking like this
{    
    "type": "FeatureCollection",
    "features": [
       {
         "type": "Feature", 
         "geometry": {
             "type": "Point", 
             "coordinates": [55.831903, 37.411961]
            }
        },
        {
         "type": "Feature", 
         "geometry": {
             "type": "Point", 
             "coordinates": [65.831903, 47.411961]
            }
        }             
    ]
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2018-05-06
@Aderus

Are you kidding me? Learn the basics

spoiler
$json['type'] = 'asdasdasd';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question