I have a slight issue whereby the API I开发者_高级运维'm using for part of my service uses a rsp stat to handle the success / error messages in XML.
So we use a form to post it data and it returns the data like the following example:
<rsp stat="ok"> <success msg="accepted" transactionid="505eeb9c43969d4919c0a6b3f7a4dfbb" messageid="a92eff8d65cf48e9c6e96702a7b07400"/> </rsp>
The following is most of the script used :
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); // ToDo: Replace the placeholders in brackets with your data. // For example - curl_setopt($ch, CURLOPT_UsERPWD, 'SMSUser:PassW0rD#'); curl_setopt($ch, CURLOPT_USERPWD, ''); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 100); $xml = curl_exec($ch); if (curl_error($ch)) { print "ERROR ". curl_error($ch) ."\n"; } curl_close($ch); print_r($xml);
The only problem is that when it is parsed and displayed via the print_r command , it only displays via source code for some strange reason and we have no idea how to display it via the page
Basically we would like a system whereby if rsp stat="ok" then "Sent" else "unsent".
Well, a simple way could be:
if (strpos($xml, 'stat="ok"') !== false) {
echo "sent";
} else {
echo "unsent";
}
http://codepad.org/pkzsfsMk
This would replace print($xml);
.
Put that code in a function, and have the function return your $xml.
Assuming you had a function called getRspStat() you could just do like:
echo getRspStat();
If you do something like that:
(see also on CodePad.org)
function xmlRequestWasSuccessful($xml) {
$result = simplexml_load_string($xml);
$result = (string)$result['stat'];
if ($result == 'ok') {
return true;
} else {
return false;
}
}
$xml = '<rsp stat="ok">
<success msg="accepted" transactionid="505eeb9c43969d4919c0a6b3f7a4dfbb" messageid="a92eff8d65cf48e9c6e96702a7b07400"/>
</rsp>';
$stat = xmlRequestWasSuccessful($xml);
you will receive 'true' boolean in the result ($stat
variable). Adapt it to support the case when there is an error. Since no details on how it looks when error occurs, this is how you can do it now:
if ($stat) {
// do something on success ('sent' something)
} else {
// do something on success (display 'unsent' message for example)
}
精彩评论