Created
March 3, 2024 20:31
-
-
Save muathendirangu/de20ca5e2952a147d0bd7967355c49cb to your computer and use it in GitHub Desktop.
A php script that retrieve a list of users and displays the name and email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Define the API URL | |
$apiUrl = "https://jsonplaceholder.typicode.com/users"; | |
try { | |
// Create a cURL resource | |
$curl = curl_init($apiUrl); | |
// Set cURL options | |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($curl, CURLOPT_TIMEOUT, 5); // Set a timeout limit (optional) | |
// Execute the request and handle errors | |
$response = curl_exec($curl); | |
$curlError = curl_error($curl); | |
// Close the cURL resource | |
curl_close($curl); | |
// Check for cURL errors | |
if ($curlError) { | |
throw new Exception("cURL Error: " . $curlError); | |
} | |
// Decode the JSON response | |
$data = json_decode($response, true); | |
// Check if decoding was successful | |
if (!is_array($data)) { | |
throw new Exception("Failed to decode JSON response."); | |
} | |
// Loop through users and display information | |
echo "** User Information **\n"; | |
foreach ($data as $user) { | |
echo "Name: " . $user['name'] . "\n"; | |
echo "Email: " . $user['email'] . "\n\n"; | |
} | |
} catch (Exception $e) { | |
// Display error message if an exception occurs | |
echo "Error: " . $e->getMessage(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment