How to fetch data through API based on form values in PHP ?

Today we will discuss how we can fetch data through API based on user submitted form values. We will used file_get_contents() function for get the API response. So we will get the user Id from user and according to that user ID fetch the user results and display it on page.


Used API: https://reqres.in/


HTML Code:


<!DOCTYPE html> 

<html> 

<head> 

    <title>Get Response Using API</title> 

    <style> 

        form { 

            margin: 30px 0px; 

        } 

        input { 

            display: block; 

            margin: 10px 15px; 

            padding: 8px 10px; 

            font-size: 16px; 

        } 

        div { 

            font-size: 20px; 

            margin: 0px 15px; 

        } 

        h2 { 

            color: green; 

            margin: 20px 15px; 

        } 

    </style> 

</head> 

<body> 

    <h2>Get Response Using API</h2> 

    <form method="post"> 

        <input type="text" name="id" placeholder="Enter user Id"> 

        <input type="submit" name="submit-btn" value="submit"> 

    </form> 

    <br> 

</body> 

</html> 


PHP Code:

<?php  

    if (isset($_POST["submit-btn"])) { 

    $id=$_POST['id'];

            $response = file_get_contents('https://reqres.in/api/users/' . $id );

            $result = json_decode($response,true);   

            echo "<pre>";

print_r ($result);

            echo "</pre>";

            // Print first name

            echo "First name: ".$result['data']['first_name'];

    } 

?> 


OUTPUT:


Result

In the above PHP code we used file_get_contents() function for fetch the data. The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

How's this above code works:

- User enter the user Id using form and submit the form.

- After Submit the form we send the user submitted ID in API URL (
https://reqres.in/api/users/' . $id) and store the API result in $response variable.

- After that using json_decode() function we decoded the API response ad store it in $result variable.

- Now we have results in our $result variable, we just need to print it. In above example I print all the full result and also print the first name.

Note: https://reqres.in provide free API for testing purpose. 


That's it for now. If you have any issue or suggestion please let me know through below comment box. Thanks!


Following are some other interesting posts, please have a look:

- How To Call an API in PHP

15 Stunning VFX Effect Shots From Famous Movies






 

Post a Comment

0 Comments