Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read XML string with PHP

Tags:

php

Eg:

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

ReadXml($xmlstr) 

Output ->

Address

to: Srinivas

from: Chennai

country : India

like image 633
Egglabs Avatar asked Aug 16 '26 22:08

Egglabs


1 Answers

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.

like image 64
Gordon Avatar answered Aug 19 '26 12:08

Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!