【问题标题】:XML to php variable [duplicate]XML到php变量[重复]
【发布时间】:2014-03-03 22:40:58
【问题描述】:

我是 XML 新手,我需要一个从这个到 php 变量的值:

<wb:countries xmlns:wb="http://www.worldbank.org" page="1" pages="1" per_page="50"   total="1">
<wb:country id="NLD">
<wb:iso2Code>NL</wb:iso2Code>
<wb:name>Netherlands</wb:name>
<wb:region id="ECS">Europe & Central Asia (all income levels)</wb:region>
<wb:adminregion id=""/>
<wb:incomeLevel id="OEC">High income: OECD</wb:incomeLevel>
<wb:lendingType id="LNX">Not classified</wb:lendingType>
<wb:capitalCity>Amsterdam</wb:capitalCity>
<wb:longitude>4.89095</wb:longitude>
<wb:latitude>52.3738</wb:latitude>
</wb:country>
</wb:countries>

这是获取xml的url:

http://api.worldbank.org/countries/nl

谁能告诉我如何在 php 变量中获取“荷兰”? 并解释它是如何工作的?

谢谢

编辑:

我收到此错误:

Warning: SimpleXMLElement::__construct(): Entity: line 1: parser error : Start tag expected, '<' not found in D:\Websites\htdocs\test\index.php on line 2

Warning: SimpleXMLElement::__construct(): http://api.worldbank.org/countries/nl in D:\Websites\htdocs\test\index.php on line 2

Warning: SimpleXMLElement::__construct(): ^ in D:\Websites\htdocs\test\index.php on line 2

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in D:\Websites\htdocs\test\index.php:2 Stack trace: #0 D:\Websites\htdocs\test\index.php(2): SimpleXMLElement->__construct('http://api.worl...') #1 {main} thrown in D:\Websites\htdocs\test\index.php on line 2

使用了这个代码:

 $object = new SimpleXMLElement('http://api.worldbank.org/countries/nl');
 $array = json_decode(json_encode($object), true);

【问题讨论】:

    标签: php xml


    【解决方案1】:

    简单,使用 PHP 内置的 SimpleXML 扩展:

    $object = new SimpleXMLElement($xmlString);
    

    这实际上是读取 XML 字符串并将其解析为 PHP 对象。

    如果你必须把它作为一个数组而不是一个对象,因为它是多维的,你可以使用这个有点脏的方法:

    $array = json_decode(json_encode($object), true));
    

    这利用了 JSON 扩展的可选 $assoc 参数(如果设置为 true,它会将其转换为关联数组,而不是简单地再次将其转换回对象。

    【讨论】:

    • 有一些错误,见编辑错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2015-11-11
    • 1970-01-01
    相关资源
    最近更新 更多