How to Read XML File in Laravel?

In this  example we will show how to read xml file in laravel?. This post we discuss on example of laravel read xml file example.  I explained simply step by step laravel read xml file. Here you will learn laravel read xml example.

You can easily read xml file in laravel 6, laravel 7 and laravel 8 version.

In this example we will simple example of convert xml to php array in laravel. So let’s, we will keep one simple example file and convert into php array.

Create xml file

In this step we will create sample.xml file in your public directory for read xml file in laravel. so let’s the following code.

<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>

Create route

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('', [UserController::class,'index']);

Create controller

In this step we will create UserController.php file and following the code for read xml file.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
  public function index()
  {
    $xmlString = file_get_contents(public_path('sample.xml'));
    $xmlObject = simplexml_load_string($xmlString);
               
    $json = json_encode($xmlObject);
    $phpArray = json_decode($json, true); 

    echo "<pre>";
    print_r($phpArray);
    exit;
  }
 
}

I hope you understand example of how to read xml file in laravel and it can help you…