I do a cURL POST and return an error response, parse it in an array, but now I have problems with xpath.
// XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<errors xmlns="http://host/project">
<error code="30" description="[] is not a valid email address."/>
<error code="12" description="id[] does not exist."/>
<error code="3" description="account[] does not exist."/>
<error code="400" description="phone[] does not exist."/>
</errors>
// Function / Class
class parseXML
{
protected $xml;
public function __construct($xml) {
if(is_file($xml)) {
$this->xml = simplexml_load_file($xml);
} else {
$this->xml = simplexml_load_string($xml);
}
}
public function getErrorMessage() {
$in_arr = false;
$el = $this->xml->xpath("//@errors");
$returned_errors = count($el);
if($returned_errors > 0) {
foreach($el as $element) {
if(is_object($element) || is_array($element)) {
foreach($element as $item) {
$in_arr[] = $item;
}
}
}
} else {
return $returned_errors;
}
return $in_arr;
}
}
// call function
$errMsg = new parseXML($arr[3]);
$errMsgArr = $errMsg->getErrorMessage();
What I would like is all the error code attribute and description values
EDIT:
OK this is print_r ($ this-> xml, true);
SimpleXMLElement Object
(
[error] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[code] => 30
[description] => [] is not a valid email address.
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[code] => 12
[description] => Id[12345] does not exist.
)
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[code] => 3
[description] => account[] does not exist.
)
)
[3] => SimpleXMLElement Object
(
[@attributes] => Array
(
[code] => 400
[description] => phone[] does not exist.
)
)
)
)
for life, I canβt understand why I can get the code and description, any thoughts?
EDIT No. 2 Okay, I think I will break it.
I use cURL to send a request to one of our servers, I parse the HTTP and xml response headers (if xml is returned). each line in the header / xml I explode into an array. therefore, if there is an error, I see an additional index for the array. Then I do something like this.
$if_err_from_header = $http_return_response[10];
// I know that index 10 is where if any the error message in xml is (the one posted above).
after that i do this:
$errMsg = new parseXML($if_err_from_header);
$errMsgArr = $errMsg->getErrorMessage();
still I canβt get the code and description from the attributes with an error, what am I missing?
β 3
, ?
$in_arr = false;
$el = $this->xml->xpath("//@code");
$el = $el == false ? array() : $el;
foreach($el as $element) {
$in_arr[] = array("code" => $element["code"], "description" => $element["description"]);
}
return $in_arr;
β 4:
, , , , , ...
$el = $this->xml->xpath("//*");