0

I am newbie to php, Here is my json file ,

{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego@m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli@hsEfFzn@QlTgNhwCs@fKwBjF","status_message":"Found route between points","status":0}

I need to extract the total_time only from the json and print the extracted total_time to a new column in a csv file,could someone please help me in that?

Black User
  • 395
  • 8
  • 24

2 Answers2

1

You need these i think.

$json = '{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego@m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli@hsEfFzn@QlTgNhwCs@fKwBjF","status_message":"Found route between points","status":0}';
$assoc = true;
$result = json_decode ($json, $assoc);
$result['total_time'] = $result['route_summary']['total_time'];

$json = json_encode($result);

Now its time to put these $json back to a file using file_put_contents.

file_put_contents('file.csv', $json );
Murad Hasan
  • 9,418
  • 2
  • 19
  • 40
0

Save your json string into a json file, load it and you can use json_decode function to load it in PHP as an array.

$string = file_get_contents('file.json');
$json = json_decode($string, true);
$totalTime = $json['route_summary']['total_time']; // 101

How to export the results to CSV file afterwards you have examples here on SO.

Elzo Valugi
  • 25,880
  • 14
  • 91
  • 114
  • The Question is not about to get the total_time only, Its about to put, _extracted total_time to a new column in a csv file_. – Murad Hasan May 26 '16 at 07:25