Read Data from XML File using PHP

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1">
        <name>John</name>
    </person>
    <person id="2">
        <name>Mary</name>
    </person>
    <person id="3">
        <name>Robert</name>
    </person>
</persons>

DOMDocument class

<?php

$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;

$doc->load('test.xml');
$root = $doc->documentElement;

$data = [];

foreach ($root->childNodes as $person) {
    $data[] = [
        'id' => (int) $person->getAttribute('id'),
        'name' => $person->getElementsByTagName('name')->item(0)->nodeValue,
    ];
}

print_r($data);

Leave a Comment

Cancel reply

Your email address will not be published.