Jump to content

XML parsing problems


Chris92

Recommended Posts

Hi, I'm working on a script that connects to a remote API and receives information in XML.

 

The problem I'm having is I can't seem to get it to parse right.

 

The information that is received is this:

 

<?xml version="1.0" encoding="UTF-8"?><response xmlns:agent="http://www.eurodns.com/agent"><result code="1000">	<msg><![CDATA[Command completed successfully]]></msg></result><resData>	<agent:balance currency="EUR">0.00</agent:balance></resData></response>

 

 

I'm trying to use the SimpleXMLElement class to parse it and this is the result I get:

 

SimpleXMLElement Object(    [result] => SimpleXMLElement Object        (            [@attributes] => Array                (                    [code] => 1000                )            [msg] => SimpleXMLElement Object                (                )        )    [resData] => SimpleXMLElement Object        (        ))

 

 

As you might notice the resData Object is for some reason empty.

 

I haven't done much XML parsing with PHP 5 before so I'm probably missing something.

 

Any help is appreciated,

 

Chris

Link to comment
https://forums.phpfreaks.com/topic/213645-xml-parsing-problems/
Share on other sites

Here's an example:

 

 

$string = <<<XML<?xml version="1.0" encoding="UTF-8"?><response xmlns:agent="http://www.eurodns.com/agent">   <result code="1000">      <msg><![CDATA[Command completed successfully]]></msg>   </result>      <resData>      <agent:balance currency="EUR">0.00</agent:balance>  <agent:balance currency="GBP">100.00</agent:balance>   </resData>   </response>XML;$xml = simplexml_load_string($string);  foreach ($xml->resData->children('http://www.eurodns.com/agent') as $agent) {echo $agent->attributes()->currency;echo $agent;echo '<hr>';} 

 

 

There's an article about it here: http://devzone.zend.com/node/view/id/688#Heading3

Thanks. The problem as you pointed out were the namespaces.

 

Here's how I managed to fix it:

 

function xmlToObject($xml, $type){$array = array();$xml = new SimpleXMLElement($this->exec($xml));foreach( $xml->resData as $value ){	$array[] = $value->children('http://www.eurodns.com/' . $type);}return $array;}

 

 

Which gave me:

 

Array(    [0] => SimpleXMLElement Object        (            [balance] => 0.00        ))

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.