To make a GET request to the REST API of GitHub and return JSON data using PHP cURL, you can follow these steps:
Step 1: Set up a new PHP file.
Create a new PHP file (e.g., github_api.php
) and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php // GitHub API endpoint $url = 'https://api.github.com/'; // Initialize cURL $curl = curl_init(); // Set the cURL options curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'User-Agent: PHP cURL', 'Accept: application/vnd.github.v3+json' ]); // Execute the cURL request $response = curl_exec($curl); // Check for errors if ($response === false) { die('cURL error: ' . curl_error($curl)); } // Close the cURL session curl_close($curl); // Print the response (JSON data) echo $response; |
In the above code, we set the GitHub API endpoint URL, initialize the cURL session using curl_init()
, and set the necessary cURL options using curl_setopt()
. We specify the URL to fetch, set CURLOPT_RETURNTRANSFER
to true to return the response as a string, and provide the required headers, including a user-agent and accept header. The Accept
header is set to specify that we want to receive the response in JSON format.
We then execute the cURL request using curl_exec()
. If there are any errors during the cURL request, we handle them by checking if $response
is false
and printing the error message using curl_error()
.
Finally, we close the cURL session using curl_close()
and print the response (JSON data) using echo $response
.
Step 2: Run the PHP script.
Save the github_api.php
file and upload it to your PHP-enabled server. Access the PHP file in a web browser, and it will make a GET request to the GitHub REST API and return the JSON data.
Note: Depending on the specific GitHub API endpoint and the type of data you want to retrieve, you may need to modify the URL and the headers accordingly.
That’s it! You have successfully created a PHP cURL script to make a GET request to the GitHub REST API and return JSON data.