I am trying to read this XML file using PHP and I have two root elements. The code that I wrote in PHP reads only one root element and when I add the other one (<action>
) it gives me an error.
I want to do something like this : if($xml->action=="register")
then print all 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 all this...
Fix your XML, it's invalid. XML files can only have 1 root element.
Example valid XML:
<?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 parameters to have 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 multiple actions:
<?xml version='1.0' encoding='ISO-8859-1'?>
<actions>
<action type="register">
<name>Johnny B</name>
<username>John</username>
</action>
</actions>
EDIT:
As I've said in my comment, your teacher should fix his XML. It is invalid. Also he should put his XML through a validator.
If you're really desperate you can introduce an articificial root element, but this is really bad practice and should be avoided at all costs:
$xmlstring = str_replace(
array('<action>','</paramters>'),
array('<root><action>', '</paramters></root>'),
$xmlstring
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With