2

Eg:

$xmlstr ='<Address><to>Sriniva</to><from>Chennai</from><country>India</county></Address>';

ReadXml($xmlstr) 

Output ->

Address

to: Srinivas

from: Chennai

country : India

6 Answers 6

12

With SimpleXML

$address = new SimpleXMLElement($xmlstr);
printf("%s\nto: %s\nfrom: %s\ncountry: %s",
       $address->getName(),
       $address->to, 
       $address->from, 
       $address->country);

or

$address = new SimpleXMLElement($xmlstr);
echo $address->getName(), PHP_EOL;
foreach($address as $name => $part) {
    echo "$name: $part", PHP_EOL;
}

Both output:

Address
to: Sriniva
from: Chennai
country: India

Just fix the closing country tag. It has a typo and is missing the r.

Sign up to request clarification or add additional context in comments.

Comments

5
<?php
$xml = simplexml_load_string("<Address>;
<to>Srinivas</to>
<from>Chennai</from>
<country>India</country>
</Address> ");



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

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

Output:

Address

to: Srinivas

from: Chennai

country : India

1 Comment

If this is an addition to your question, please edit your original question instead of giving it as an answer.
1

you have an error in your xml string

country tag is closed wrongly county

right xml

$xmlstr ='<Address><to>Sriniva</to><from>Chennai</from><country>India</country></Address>';

to change XML to array you can simply do this

$address = simplexml_load_string($xmlstr, "SimpleXMLElement", LIBXML_NOCDATA);

    $address = json_encode($address);
    $address = json_decode($address, TRUE);

then with you can access $address as

echo $address["to"];

prints Sriniva

print_r($address)

prints

Array
(
   [to] => Sriniva
   [from] => Chennai
   [country] => India
)

Comments

0

You could use the XML functions, but using XSLT would be another decent option.

Comments

0

You might also want to have a look to the PHP xpath.

They use almost your same code in the example :)

Comments

0

Your Xml is not Valid so, its not Possible to do it with the xml tools php provides.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.