Generate XML in Laravel – Simple Way
Hello viewers, in this article I will show you how to generate XML file in Laravel in a simple way.
So let’s get started!
Step 1: Create a new controller as your need. Let’s say My controller name is “XmlController”.
For this you can run the below command.
php artisan make:controller XMLController
In the controller, create a function named e.g. “index”, fetch your desired data and pass to the view with headers for xml and download the xml. You can provide the XML file name in “’Content-Disposition’ => ‘attachment; filename=’.$category->name.’.xml’,”
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use App\Category; class XmlController extends Controller { public function index() { $category = Category::first(); return response()->view('xml.categories', [ 'category' => $category ]) ->withHeaders([ 'Content-Type' => 'text/xml', 'Content-Description' => 'File Transfer', 'Content-Disposition' => 'attachment; filename='.$category->name.'.xml', 'Content-Transfer-Encoding' => 'binary', ]); } }
Step 2: Create a view with provided XML file data (e.g: xml.blade.php)
Create a view with provided XML file data (e.g: xml.blade.php)
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?> <Root> <Record> <ID>{{ $category->id}}</ID> <TITLE>{{ $category->title}}</TITLE> <NAME>{{ $category->name}}</NAME> <CREATED>{{ $category->created_at}}</CREATED> ……………………………OTHER DATA AS PER YOUR NEED…………………………………………… </Record> </Root>
Step 3: Register in route file
Define the route as per your requirement. I have defined the below way.
Route::get('genxml', 'XmlController@index')->name('genxml');
Check Out More Resources:
Articles:
Website: https://laravelplug.com/
YouTube Channel: https://www.youtube.com/channel/UCnTxncHQcBSNs4RCuhWgF-A?sub_confirmation=1
WordPress Playlist: https://www.youtube.com/watch?v=8VvXzFAFwQU&list=PLVoVZqAh8dTLHZ51egvEU7dsOrRCSIMWx
Tools Playlist: https://www.youtube.com/watch?v=gTQoUn3BQkM&list=PLVoVZqAh8dTK-DWHBGWOEEvzvPQrgFne-
WordPress Tutorials: https://laravelplug.com/category/wordpress/
Laravel Tutorials: https://laravelplug.com/category/laravel/
PHP Tutorials: https://laravelplug.com/category/php/
SQL Tutorials: https://laravelplug.com/category/sql/
Various Tips: https://laravelplug.com/category/tips/
Useful Tools: https://laravelplug.com/category/tools/
Socials:
Twitter: https://twitter.com/LaravelPlug
Pinterest: https://www.pinterest.com/LaravelPlugCom/
Facebook: https://www.facebook.com/groups/1020759861842360
Mail: info@laravelplug.com
#Laravel #XML
That’s All. Feel free to knock me. Thanks.