PHP Get, Write, Read, Load, JSON Data from URL
Php 06-Apr-2022

PHP Get, Write, Read, Load, JSON Data from URL

PHP Get, Write, Read, Load, JSON Data from external URL; In this tutorial. We will learn, how to get data from JSON file in PHP and how to Get, Load, Read, Save/Write, JSON File from Url in PHP.

PHP Get, Write, Read, Load, JSON Data from URL

Use the following examples to get, read, write and load json data from url or apis in php; as follows:

  • 1. PHP read JSON file From URL
  • 2. Get JSON File Data From URL in PHP & Convert JSON to Array PHP
  • 3. Convert JSON to Object PHP
  • 4. PHP write or save JSON to a JSON file

1. PHP read JSON file From URL

You can use the PHP file_get_contents() function that is used to get or read or load file from the given path (Url or Source).

In the following example, we will use PHP to read data from the URL file. After that, we will print the data to the web page.

Example-1

<?php
 
$url = 'your json file path';
//read json file from url in php
$readJSONFile = file_get_contents($url);
print_r($readJSONFile); // display contents
 
?>

2. Get JSON File Data From URL in PHP & Convert JSON to Array PHP

You can use the file_get_contents() function and json_decode() function of PHP.

  • File get_get_conents() get that is used to get or read file from the given path (Url or Source).
  • json_decode() function of PHP, which is used to convert JSON file contents to PHP Array

Example-1

<?php
 
$url = 'your json file path';
 
//read json file from url in php
$readJSONFile = file_get_contents($url);
 
//convert json to array in php
$array = json_decode($readJSONFile, TRUE);
var_dump($array); // print array
 
?>

3. Convert JSON to Object PHP

You can convert JSON file data to the PHP objects. You can use the json_decode() without passing the TRUE in it. Because by default, the PHP json_decode function will convert the JSON data into an object.

<?php
 
$url = 'your json file path';
 
//read json file from url in php
$readJSONFile = file_get_contents($url);
 
//convert json to array in php
$array = json_decode($readJSONFile);
var_dump($array); // print array
 
?>

4. PHP write or save JSON to a JSON file

You can use the file_put_contents() function of PHP, which is used to write or save data from a given path of the JSON file or text file.

<?php
 
$path = 'Url file path';
 
$data = 'Hello world';
 
file_put_contents($path, $data)
 
?>