I'm still learning Laravel 5.3 and am using Guzzle to connect to an API to download an already formatted xml file that I need to save to local user's pc for further usage.
I have created a download button:
<a href="{{ '/vendorOrder' }}" class="btn btn-large pull-right> Download Order </a>
I created a controller called OrderController.php:
<?php
namespace App\Http\Controllers\edi;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as GuzzleHttpClient;
class OrderController extends Controller
{
public function vendorOrder()
{
try {
$filename = 'order.xml';
$path = storage_path($filename)';
$client = new GuzzleHttpClient();
$apiRequest = $client->request('GET', 'Https://urlapi') [
'headers' => [
'Authorization' => 'Basic QVBJVGVzdFVzZXIsIFdlbGNvbWVAMTIz',
'ContractID' => 'aa659aa2-4175-471f',
'Accept' => 'text/xml'
],
]);
$content = ($apiRequest->getBody()->getContents());
return response::download(file_put_contents($path, $content), '200', [
'Content-Type' => 'text/xml',
'Content-Disposition' => 'attachment; filename="'.$filename.'"'
]);
} catch (RequestException $re) {
echo $re;
}
}
}
and the route:
Route::get('/vendorOrder', 'edi\OrderController@vendorOrder');
I'm able to connect just fine, and the contents of the xml display just fine when I use:
return response($content, '200')->header('content-type', 'text/xml');
however when I use:
return response::make(file_put_contents($path, $content), '200', [
'Content-Type' => 'text/xml',
'Content-Disposition' => 'attachment; filename="'.$filename.'"'
]);
as in controller above, I'm able to download a file called order.xml (as expected) but the contents is just a single number ie "1179866". No xml tags or the xml content or anything else - just the number.
Any help would be appreciated
In both cases you are wrong.
response::download
What are the arguments to response::download
? See a manual:
Response::download($pathToFile);
See - path to file. In your code:
return response::download(file_put_contents($path, $content), // other arguments
result of file_put_contents
is not a path to file.
Read a manual and see that file_put_contents
This function returns the number of bytes that were written to the file, or FALSE on failure.
Solution:
$path = 'my/path/here';
file_put_contents($path, $content);
return response::download($path, // other arguments
response::make
. Same error.See a manual:
response::make($contents, $statusCode);
Again - first argument is $contents
.
In your code
response::make(file_put_contents($path, $content),
contents if the result of file_put_contents
execution, which is see above.
Solution:
response::make($content, 200, $headers);