[Tips] How to Parse JSON in PHP from URL

0
32

If you want to parse JSON in PHP from URL, you can try to use file_get_contents API.

How to Parse JSON in PHP from URL
How to Parse JSON in PHP from URL

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

Note:
If you’re opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().


$json_url = "https://maps.googleapis.com/maps/api/directions/json?origin=" . urlencode($_POST['address1']) . "&destination=" . urlencode($_POST['address2']) . "&key=AIzaSyCMcrBGtTId8BXGD6UgcRatWSvBAaCH5mQ";

OR


$json_url = "https://maps.googleapis.com/maps/api/directions/json?origin=lê văn sĩ, quận 3&destination=la văn cầu, vũng tàu"&key=AIzaSyCMcrBGtTId8BXGD6UgcRatWSvBAaCH5mQ";




$obj = file_get_contents($json_url);


$result =  json_decode($obj);

Use file_get_contents to get JSON file with URL, then decode obj to array $result

How to Parse JSON in PHP from URL

Example: 

JSON data from result same as the above image:

If you want to access this value:

How to Parse JSON in PHP from URL

Your code here:


$result->{"routes"}[0]->{"legs"}[0]->{"distance"}->{"text"};  // 102




$result->{"routes"}[0]->{"legs"}[0]->{"distance"}->{"value"};    // 102088


$result->{"routes"}[0]->{"copyrights"};   // Map data @2017 Google


If you have any feedback, leave your comment, we can discuss about it!
Zidane


Related topic:

[C#] Read JSON file

[C#] Convert JSON to string array