How to read json file from url in laravel?

by cortez.connelly , in category: PHP Frameworks , 6 months ago

How to read json file from url in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 6 months ago

@cortez.connelly 

To read a JSON file from a URL in Laravel, you can use the file_get_contents function along with json_decode function. Here is an example code snippet on how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use IlluminateSupportFacadesHttp;

$url = 'https://example.com/data.json';
$response = Http::get($url);

if ($response->successful()) {
    $data = $response->json();
    
    // Process the JSON data
    foreach ($data as $item) {
        // Do something with each item
    }
} else {
    // Handle error if request was not successful
    $errorMessage = $response->body();
    // Log or display the error message as needed
}


In this example, we first make a GET request to the URL using Laravel's Http::get method. We then check if the response was successful using the successful() method. If successful, we use the json() method to convert the response body to an associative array, and then we can process the JSON data as needed.


Remember to include use IlluminateSupportFacadesHttp; at the top of your controller or wherever you are using this code.