hrishi
hrishi

Reputation: 1656

Read attribute value from XML which contains prefix with colon in element name and attribute name

I have element in XML like below

<user:name test:one = "firstUser" />

I use PHP DOM Xpath to read XML

$doc = new DOMDocument();

$xpath = new DOMXPath($doc);
$xml = simplexml_load_file(file path here);
echo '<pre>'; print_r($xml);

and output is blank

SimpleXMLElement Object
(
)

If I try removing : and prefix like below

<name one = "firstUser" /> 

then it reads element. output is

SimpleXMLElement Object
(
    [name] => SimpleXMLElement Object
    (
        [@attributes] => Array
        (
            [one] => firstUser
        )
    )
)

How I can read element value with prefix and colon (:)

Updated : sample XML file

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:test="http://www.w3.org/2001/XMLSchema"  xmlns:user="http://www.w3.org/2001/XMLSchema">
    <user:name test:one = "firstUser" />
    <name second = "secondUser" />
</root>

Upvotes: 1

Views: 655

Answers (1)

ishegg
ishegg

Reputation: 9927

Use DOMDocument to go through the document:

<?php
$doc = new DOMDocument();
$doc->load("file.xml");
$root = $doc->getElementsByTagName("root");
echo "<pre>";
foreach ($doc->getElementsByTagName("name") as $users) {
    echo $users->nodeName.":";
    foreach ($users->attributes as $attr) {
        echo $attr->name." ".$attr->value."<br>";
    }
    echo "<br>";
}

Demo (XML loaded from string)

Upvotes: 2

Related Questions