How To Read XML File in Laravel 8 – Example

Reading Time: 3 minutes

Inside this article we will see How to read XML file in laravel 8. There are actually very few simple steps and also you can follow this step in any PHP and it’s framework. This is not laravel specific.

To know the topic, reading xml file in laravel we will consider a sample xml and read it in code.


Above image is view of sample xml file and it’s data. You can download this

Let’s get started.

Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

composer create-project --prefer-dist laravel/laravel blog

To start the development server of Laravel –

php artisan serve


Assuming laravel already installed inside your system.

Create Controller

We need to create a controller where we will parse or read xml data string from file. Open laravel project into shell or terminal and type this command.

To create Controller –

$ php artisan make:controller ReadXmlController

It will create a file inside /app/Http/Controllers.

Open up the created file ReadXmlController.php into editor


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ReadXmlController extends Controller
    public function index()
        $xmlDataString = file_get_contents(public_path('sample-course.xml'));
        $xmlObject = simplexml_load_string($xmlDataString);
        $json = json_encode($xmlObject);
        $phpDataArray = json_decode($json, true); 
        // echo "<pre>";
        // print_r($phpDataArray);
  • public_path(‘sample-course.xml’) XML file should be placed in public directory. public_path returns the path upto /public folder
  • simplexml_load_string($xmlDataString); It’s a PHP function used to read xml file

Create Route

Open web.php file from /routes

//.. other code

# Import controller
use App\Http\Controllers\ReadXmlController;

Route::get("read-xml", [ReadXmlController::class, "index"]);

Application Testing

Run this command into project terminal to start development server,

php artisan serve

Open up the URL – http://localhost:8000/read-xml

We hope this article helped you to learn about i.e How To Read XML File in Laravel 8 Tutorial in a very detailed way. To save data From XML file to Database Click here to go.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.