How to get json data from link in php?

How to get json data from link in php?

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.

You should also read this PHP JSON posts:

  • Convert Array To JSON, Object To JSON
  • PHP JSON Decode Example

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)

?>

  1. Functions: Remove First Character From String PHP
  2. Remove Specific/Special Characters From String In PHP
  3. How to Replace First and Last Character From String PHP
  4. Reverse String in PHP
  5. Array Push, POP PHP | PHP Array Tutorial
  6. PHP Search Multidimensional Array By key, value and return key
  7. json_encode()- Convert Array To JSON | Object To JSON PHP
  8. PHP remove duplicates from multidimensional array
  9. PHP Remove Duplicate Elements or Values from Array PHP

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

View all posts by Admin


A common use of JSON is to read data from a web server, and display the data in a web page.

This chapter will teach you how to exchange JSON data between the client and a PHP server.


The PHP File

PHP has some built-in functions to handle JSON.

Objects in PHP can be converted into JSON by using the PHP function json_encode():

PHP file

<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$myJSON = json_encode($myObj);

echo $myJSON;
?>

Show PHP file »

The Client JavaScript

Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above:

Example

Use JSON.parse() to convert the result into a JavaScript object:

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "demo_file.php");
xmlhttp.send();

Try it Yourself »



PHP Array

Arrays in PHP will also be converted into JSON when using the PHP function json_encode():

PHP file

<?php
$myArr = array("John", "Mary", "Peter", "Sally");

$myJSON = json_encode($myArr);

echo $myJSON;
?>

Show PHP file »

The Client JavaScript

Here is a JavaScript on the client, using an AJAX call to request the PHP file from the array example above:

Example

Use JSON.parse() to convert the result into a JavaScript array:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj[2];
}
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();

Try it Yourself »


PHP Database

PHP is a server side programming language, and can be used to access a database.

Imagine you have a database on your server, and you want to send a request to it from the client where you ask for the 10 first rows in a table called "customers".

On the client, make a JSON object that describes the numbers of rows you want to return.

Before you send the request to the server, convert the JSON object into a string and send it as a parameter to the url of the PHP page:

Example

Use JSON.stringify() to convert the JavaScript object into JSON:

const limit = {"limit":10};
const dbParam = JSON.stringify(limit);
xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xmlhttp.open("GET","json_demo_db.php?x=" + dbParam);
xmlhttp.send();

Try it Yourself »

Example explained:

  • Define an object containing a "limit" property and value.
  • Convert the object into a JSON string.
  • Send a request to the PHP file, with the JSON string as a parameter.
  • Wait until the request returns with the result (as JSON)
  • Display the result received from the PHP file.

Take a look at the PHP file:

PHP file

<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$stmt = $conn->prepare("SELECT name FROM customers LIMIT ?");
$stmt->bind_param("s", $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp);
?>

PHP File explained:

  • Convert the request into an object, using the PHP function json_decode().
  • Access the database, and fill an array with the requested data.
  • Add the array to an object, and return the object as JSON using the json_encode() function.

Use the Data

Example

xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text = "";
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}

Try it Yourself »


PHP Method = POST

When sending data to the server, it is often best to use the HTTP POST method.

To send AJAX requests using the POST method, specify the method, and the correct header.

The data sent to the server must now be an argument to the send() method:

Example

const dbParam = JSON.stringify({"limit":10});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text ="";
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_db_post.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

Try it Yourself »

The only difference in the PHP file is the method for getting the transferred data.

PHP file

Use $_POST instead of $_GET:

<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_POST["x"], false);

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$stmt = $conn->prepare("SELECT name FROM customers LIMIT ?");
$stmt->bind_param("s", $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp);
?>



How to fetch json data from url in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

How can I get JSON data from URL?

Get JSON From URL Using jQuery getJSON(url, data, success) is the signature method for getting JSON from an URL. In this case, the URL is a string that ensures the exact location of data, and data is just an object sent to the server. And if the request gets succeeded, the status comes through the success .

How display JSON data from URL in HTML?

“how to get json data from url in html” Code Answer's.
let url = 'https://example.com';.
fetch(url).
. then(res => res. json()).
. then((out) => {.
console. log('Checkout this JSON! ', out);.
. catch(err => { throw err });.