Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sarathiscookie's avatar

How to download file from external api response source using Laravel?

I need to download files from an api response source using Laravel.

An example api - (http://webservice.test.de/merchants/orders/getOrderInvoice?key=1234567894&format=json&order_no=444555666.

After calling this API, I got JSON response. JSON response are given below.

{
    "result": {
        "success": "1",
        "invoice": {
            "src": "webservice.test.de/docs/invoice?secure_key=333444555666777888&key= 1234567894",
            "filename": "Invoice_12345-234566.pdf"
        }
    }
}

When I copy this src url (['result']['invoice']['src']) and paste on browser, then hit enter key, a pdf file (Invoice_12345-234566.pdf) will download.

How can I download file from src using Laravel?

##Laravel Code

public function curl($url) 
{
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 $result = curl_exec($ch);
 curl_close($ch);
 $jsonDecodedResults = json_decode($result, true);
 return $jsonDecodedResults;
}

$getOrderInvoice = 'http://webservice.test.de/merchants/orders/getOrderInvoice?key=1234567894&format=json&order_no=444555666';

$jsonDecodedResults = $this->curl($getOrderInvoice); // Here I will get JSON response.

if( $jsonDecodedResults['result']['success'] === '1' ) {

     // Here I will get the url source and filename
     $fileSource = $jsonDecodedResults['result']['invoice']['src'];  
     $fileName = $jsonDecodedResults['result']['invoice']['filename'];
     $headers = ['Content-Type: application/pdf'];

     return response()->download($fileSource, $fileName, $headers); // Here I need to change. Any help would be appreciated.

}
0 likes
1 reply
soron25's avatar

Try this:


public function curl($url) 
{
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 $result = curl_exec($ch);
 curl_close($ch);
 $jsonDecodedResults = json_decode($result, true);
 return $jsonDecodedResults;
}

$getOrderInvoice = 'http://webservice.test.de/merchants/orders/getOrderInvoice?key=1234567894&format=json&order_no=444555666';

$jsonDecodedResults = $this->curl($getOrderInvoice); // Here I will get JSON response.

if( $jsonDecodedResults['result']['success'] === '1' ) {

     // Here I will get the url source and filename
     $fileSource = $jsonDecodedResults['result']['invoice']['src'];  
     $fileName = $jsonDecodedResults['result']['invoice']['filename'];
     $headers = ['Content-Type: application/pdf'];

   /* Do the URL validation if required $fileSource? */ 
    
     return redirect($fileSource);

}

Please or to participate in this conversation.