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.

<name>Belgian Waffles</name>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<name>Strawberry Belgian Waffles</name>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<name>Berry-Berry Belgian Waffles</name>
<description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<name>French Toast</name>
<description>Thick slices made from our homemade sourdough bread</description>
<name>Homestyle Breakfast</name>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>

Create route


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.


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>";

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