How can I parse XML with multiple root elements using PHP?

I am trying to read this XML file using PHP, and I have two root elements. The code I wrote in PHP reads only one root element, and when I add another ( <action>), it gives me an error. I want to do something like this: if($xml->action=="register")then print all the parameters.

This is my xml file:

<?xml version='1.0' encoding='ISO-8859-1'?>
<action>register</action>
<paramters>
    <name>Johnny B</name>
    <username>John</username>    
</paramters>

And this is my PHP script:

<?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach($xml->children() as $child)
{
    echo $child->getName() . ": " . $child . "<br />";
}
?>

I really don't know how to do this ...

+3
source share
3 answers

Correct your XML, it is invalid. XML files can contain only one root element.

Valid XML Example:

<?xml version='1.0' encoding='ISO-8859-1'?>
<action>
    <type>register</type>
    <name>Johnny B</name>
    <username>John</username>
</actions>

Or, if you want only the parameters to have their own elements:

<?xml version='1.0' encoding='ISO-8859-1'?>
<action type="register">
    <name>Johnny B</name>
    <username>John</username>
</actions>

or if you want some action:

<?xml version='1.0' encoding='ISO-8859-1'?>
<actions>
    <action type="register">
        <name>Johnny B</name>
        <username>John</username>
    </action>
</actions>

EDIT

, XML. . XML .

, , , :

$xmlstring = str_replace(
    array('<action>','</paramters>'),
    array('<root><action>', '</paramters></root>'),
    $xmlstring
);
+3

. XML : , , . , , , XML. , . , :

<!DOCTYPE wrapper [
<!ENTITY e SYSTEM "my.xml">
]>
<wrapper>&e;</wrapper>

XML.

+2

As this is an invalidxml file , you can do the following trick.

  • Insert dummy start tag in second line as <dummy>
  • End with </dummy>

Happy parsing;)

0
source

All Articles