How to Read XML File in Laravel 10

In my Laravel 10 development journey, I often encountered scenarios where I needed to read and extract data from XML files. While there are several packages available for XML parsing in Laravel, I wanted to explore a solution that doesn't rely on external dependencies.

In this article, I will guide you through the process of reading an XML file in Laravel 10 without using any additional packages.

By following this step-by-step guide, you will learn how to seamlessly integrate XML file reading functionality into your Laravel 10 application using Laravel's built-in features. We will cover the necessary steps, from setting up the XML file to extracting data from it.

Let's dive in and uncover the process of reading XML files in Laravel 10 without relying on packages

Step 1: Set up the XML File

Create or obtain an XML file that you want to read in your Laravel 10 application. Make sure you have the file stored in a location accessible within your project.

 

Step 2: Create a Route

Open your routes/web.php file and define a route to handle the XML file reading. For example:

Route::get('/read-xml', 'App\Http\Controllers\XmlController@readXml');

 

Step 3: Create a Controller

Generate a controller named XmlController by running the following Artisan command.

php artisan make:controller XmlController

Open the XmlController file in the app/Http/Controllers directory.

 

 

Step 4: Implement the Read XML Logic

Inside the XmlController, import the necessary classes.

use Illuminate\Support\Facades\File;
use SimpleXMLElement;

Then, create a method named readXml to handle the reading of the XML file.

public function readXml()
{
    $filePath = storage_path('app/xml/file.xml'); // Update with the actual path to your XML file

    if (File::exists($filePath)) {
        $xmlString = File::get($filePath);
        $xml = new SimpleXMLElement($xmlString);
        
        // Process the XML data as needed
        // Example: Retrieve values from specific elements
        $title = (string) $xml->title;
        $author = (string) $xml->author;
        
        // Return the extracted data or perform any further actions
        return response()->json([
            'title' => $title,
            'author' => $author,
        ]);
    }
    
    return response()->json(['error' => 'XML file not found.']);
}

 

Using simplexml_load_string() Function

simplexml_load_string() is a built-in PHP function that allows you to parse an XML string and convert it into a SimpleXMLElement object. This function is particularly useful when working with XML data in Laravel or any PHP application.

Here's an example of how you can use simplexml_load_string() to parse an XML string.

<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
  
class XMLController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $xmlString = file_get_contents(public_path('file.xml'));
        $xmlObject = simplexml_load_string($xmlString);
                   
        $json = json_encode($xmlObject);
        $phpArray = json_decode($json, true); 
   
        dd($phpArray);
    }
}

Here's an example of how you can use simplexml_load_string() to parse an XML string:

$xmlString = "<book>
    <title>Harry Potter and the Chamber of Secrets</title>
    <author>J.K. Rowling</author>
</book>";

$xml = simplexml_load_string($xmlString);

// Accessing elements and attributes
$title = $xml->title;
$author = $xml->author;

// Printing the values
echo "Title: " . $title . "<br>";
echo "Author: " . $author;

In this example, we have an XML string representing a book with a title and author. By using simplexml_load_string(), we convert the XML string into a SimpleXMLElement object called $xml.

We can then access the elements within the XML using object syntax ($xml->elementName) and retrieve their values.

By running the above code, you will see the following output:

Title: Harry Potter and the Chamber of Secrets
Author: J.K. Rowling

 

Step 5: Test the XML Reading

Start your Laravel development server by running the following command.

php artisan serve

Then, access the defined route (/read-xml) in your browser. If the XML file exists and can be read successfully, you should see a JSON response containing the extracted data from the XML file.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS