Question

I'm new with XML and I need a value from this into a php variable:

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

This is the url to get the xml:

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

Can someone tel me how i get 'Netherlands' in a php variable? And explain how it works?

Thanks

edit:

I'm getting this errors:

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

used this code:

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

No correct solution

OTHER TIPS

Simple, use PHP's built in SimpleXML extension:

$object = new SimpleXMLElement($xmlString);

What this does is it essentially reads the XML string and parses it into a PHP object.

If you must have it as an array instead of an object, since it's multidimensional you can use this somewhat dirty method:

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

This exploits the JSON extension for it's optional $assoc parameter (if it's set to true, it will convert it to an associative array as opposed to simply converting it back to an object again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top