开发者

How to read XML string with PHP

开发者 https://www.devze.com 2022-12-21 07:50 出处:网络
Eg: $xmlstr =\'<Address><to>Sriniva</to><from>Chennai</from><country>India</county></Address>\';

Eg:

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

ReadXml($xmlstr开发者_如何学编程) 

Output ->

Address

to: Srinivas

from: Chennai

country : India


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.


<?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


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
)


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


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

They use almost your same code in the example :)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号