如何用PHP读取XML字符串

Egg*_*abs 2 php

例如:

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

ReadXml($xmlstr) 
Run Code Online (Sandbox Code Playgroud)

输出 - >

地址

致:Srinivas

来自:Chennai

国家:印度

Gor*_*don 10

使用SimpleXML

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

要么

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

两个输出:

Address
to: Sriniva
from: Chennai
country: India
Run Code Online (Sandbox Code Playgroud)

只需修复结束country标记即可.它有一个拼写错误并且缺少r.


Egg*_*abs 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 />";
  }
?>
Run Code Online (Sandbox Code Playgroud)

输出:

地址

致:斯里尼瓦斯

来自: 钦奈

国家 : 印度