Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tips] How to "Parse JSON in PHP from URL"

Friday 3 March 2017
|
Read: Completed in minutes

[Tips] How to "Parse JSON in PHP from URL"

JSON, or JavaScript Object Notation, is a popular data format that is widely used in web development. JSON is easy to read and write, and can store complex data structures such as arrays, objects, and nested values. JSON is often used to exchange data between web servers and clients, or to store data in local files or databases.

PHP, or Hypertext Preprocessor, is a powerful scripting language that runs on the server side. PHP can handle various tasks such as processing forms, sending emails, connecting to databases, and generating dynamic web pages. PHP can also work with JSON data, either by creating JSON strings from PHP variables, or by parsing JSON strings into PHP variables.

Parsing JSON in PHP means converting a JSON string into a PHP variable that can be manipulated and used in the PHP code. Parsing JSON in PHP can be useful for many purposes, such as fetching data from an API, reading data from a file, or validating data from a user input.

One way to parse JSON in PHP is to use the built-in function json_decode(). This function takes a JSON string as an argument and returns a PHP variable that corresponds to the JSON value. The json_decode() function can also take an optional second argument that specifies whether to return an associative array or an object. By default, the function returns an object, but if the second argument is set to true, it returns an associative array.

To parse JSON in PHP from a URL, we need to first get the JSON string from the URL using another built-in function called file_get_contents(). This function reads the contents of a file or a URL and returns it as a string. We can then pass this string to the json_decode() function and get the PHP variable that represents the JSON data.

Here is an example of how to parse JSON in PHP from a URL:

How to "Parse JSON PHP from URL"

         
// The URL that contains the JSON data
$url = "https://example.com/api/data.json";

// Get the JSON string from the URL
$json = file_get_contents($url);

// Parse the JSON string into a PHP variable
$data = json_decode($json, true);

// Print the PHP variable
print_r($data);

This code will output something like this:

Array(
	[name] => John Doe
	[age] => 25
	[hobbies] => Array(
		[0] => Reading
		[1] => Coding
		[2] => Gaming
	)
)
      

We can now access and use the elements of the $data variable in our PHP code. For example, we can print the name of the person like this:

echo "The name is " . $data["name"] . "\n";

This will output:

The name is John Doe

We can also loop through the hobbies array and print each hobby like this:
      
echo "The hobbies are:\n";
foreach ($data["hobbies"] as $hobby) {
	echo "- " . $hobby . "\n";
}
      
This will output:

The hobbies are:
•  Reading
•  Coding
•  Gaming

 

So 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

As you can see, parsing JSON in PHP from a URL is not very difficult. You just need to use two built-in functions: file_get_contents() and json_decode(). With these functions, you can easily work with JSON data in your PHP projects.

I hope this description was helpful for you. If you want to learn more about how to parse JSON in PHP, you can check out these resources:

•  [PHP Manual: json_decode]

•  [PHP Manual: file_get_contents

 

Related topic:

[C#] Read JSON file

[C#] Convert JSON to string array

Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about How to "Parse JSON in PHP from URL" , please share them in the comments below. I would love to hear from you and discuss this topic further
✋✋✋✋  Webzone Tech Tips Zidane, all things tech tips web development  - I am Zidane, See you next time soon ✋✋✋✋

🙇🏼 We Appreciate Your Comments and Suggestions - Webzone - all things Tech Tips web development 🙇🏼
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com