How To Create a JSON File in PHP With Fake Data API User

haidi nurhadinata
3 min readAug 22, 2020

--

source

For your information, I use PHP version 7.2.24, apache version 2.4.29 as a web server and my operating system Ubuntu 18 Linux. If when you try not working or else, you have to check version PHP and your operating system. I suggest you must equalize version PHP and operating system by this article.

I use the API generator user fake from website reqres.in for fetch data fake user. And then for testing API use app Postman so that we know that API it’s work or not.

This tutorial you must know basic about PHP, Apache2, API, cURl PHP, and JSON. So that you don’t get confused when you try this article.

Step 1

I created a file PHP with a name “createJson.php”(whatever you want to name your file PHP). make sure path your file PHP in “/var/www/html” if you use operating system Linux Ubuntu.

Step 2

For fetch data from API in PHP using cURL PHP and then show to web.

//createJson.php<?php
$headers = array(
'Content-Type : application/json',);$curl = curl_init('https://reqres.in/api/users?page=1');curl_setopt($curl, CURLOPT_HTTPHEADER , $headers);curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);curl_setopt(CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');$response = curl_exec($curl);$err = curl_error($curl);curl_close($curl);$data = json_decode($response,true);echo json_encode($data['data']);

View results from createJson.php.

data array fake user from API

Step 3

We create file json by name “Users.json” in path same with file “createJson.php”. Insert data users from API to file “Users.json” like this.

$insert = file_put_contents('Users.json', $json);if($insert){echo "insert to file json work!.";}else{echo "sorry, not complete insert to file json.";}

Full source code like this.

// createJson.php
<?php
$headers = array('Content-Type : application/json',);$curl = curl_init('https://reqres.in/api/users?page=1');curl_setopt($curl, CURLOPT_HTTPHEADER , $headers);curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);curl_setopt(CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');$response = curl_exec($curl);$err = curl_error($curl);curl_close($curl);$data = json_decode($response,true);$json = json_encode($data['data']);$insert = file_put_contents('Users.json', $json);if($insert){echo "insert to file json work!.";}else{echo "sorry, not complete insert to file json.";}

the result from insert data json.

it’s work insert to file json

Conclusion

we’ve studied how to get data from API and then insert to file JSON by PHP. If you used Operating System Ubuntu Linux, I’m sure that you get a lot of problems.

If you have question you can ask or you have any critic to my e-mail haidinurhadinata@gmail.com.
thank you for your attention.

--

--

haidi nurhadinata

Laravel | React | Redux | Nextjs | TypeScript | Tailwind