0

I need to parse this string:

<RESPONSE>
<status>200</status>
<credits>100.00</credits>
</RESPONSE>

It seems XML but I think that it is not. In effect, no other tags or other.

I need to parse and extract the , so I can print an output, for example,

"<p>Available credits: '.$credits.'</p>"

Of course I tried SimpleXMLElement but it doesn't recognize the XML.

Could you help me?

Thank you

sineverba
  • 5,059
  • 7
  • 39
  • 84

2 Answers2

1

Your XML is valid but lacks XML header. Basically after you add the header you should be able to use SimpleXML:

$xml = "<?xml version='1.0' standalone='yes'?>\n" . $similXML;

$response = new SimpleXMLElement($xml);

echo $response->credits;
Vladimir Bashkirtsev
  • 1,334
  • 11
  • 24
  • Thank you. In effect adding the header all goes ok. But, I have another problem. I get the $similXML from a CURL call, and PHP add header at the end... I cannot put it in front :( This is my code: $header = ''; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $postUrl); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $response = curl_exec($ch); $result = $header.$response; print_r($result); – sineverba Jun 17 '14 at 09:51
  • When I print_r($result), I obtain first the response from CURL and after the header... :( – sineverba Jun 17 '14 at 09:52
  • 1
    You missing curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); before curl_exec(). In effect you see $similXML printed by cURL, not by your print_r() as $response is empty (having boolean true only). – Vladimir Bashkirtsev Jun 17 '14 at 09:58
  • You don'T need curl, PHP support HTTP and SimeplXMLElement can open HTTP URLs directly. – hakre Jun 19 '14 at 15:27
  • Internal HTTP client of SimpleXMLElement is not that good in handling http errors. cURL returns more diagnostic information which allows to actually handle http errors properly. – Vladimir Bashkirtsev Jun 19 '14 at 20:27
0

If you only need a few static values you can extract them yourself.

To get the credits you would do:

if (preg_match('/<credits>([0-9.]+)<\/credits>/', $response, $matches) {
  $credits = $matches[1];
}
colburton
  • 4,685
  • 2
  • 26
  • 39