Sushant
Sushant

Reputation: 142

Get string XML node value as string in laravel / PHP

I got an XML response from server. This is the response.

<response>
     <response_code>Success</response_code>
</response>

I stored this response in a variable $response. There is another similar response for failure. So, I just want to check if the node value is Success or Failure.

What I do is this:

$xmlString =simplexml_load_string($response) or die("Error: Cannot create object"); 

$resp_code =  (string)$xmlString->response_code;

if($resp_code == 'Success'){
  echo 'Successfully completed';
}
else{
  echo 'not done';
}

But the if condition doesn't work. I guess the $resp_code is not string here.

I also tried $xmlString->response_code->__toString(); but didn't work. What am I missing? Somebody please help.

P.S: I'm doing this in Laravel, if that helps.

Upvotes: 0

Views: 1704

Answers (2)

Mark
Mark

Reputation: 1376

Alternatively,

If you would like to get away from PHP's pretty convoluted xml handling, you can use my package:

https://github.com/mtownsend5512/xml-to-array

$xmlArray = xml_to_array($response);

$resp_code =  $xmlArray['response_code'];

if($resp_code == 'Success'){
  echo 'Successfully completed';
}
else{
  echo 'not done';
}

Upvotes: 0

Jonathan K
Jonathan K

Reputation: 550

After testing your code, its works perfectly.

The simplexml_load_string() function parses the given response as an object and by using type casting, your output is definitely a string.

If you keep getting results other than a success, its probably because the response the server is giving you isn't a success, or there might be a mix in the use of uppercase and lowercase alphabet.

Try editing this part of your code

if(strtolower($resp_code) == 'success'){
  echo 'Successfully completed';
} else{
  echo 'not done';
}

That should take of any mix up of such nature.

Upvotes: 1

Related Questions