【发布时间】:2011-02-21 02:11:34
【问题描述】:
我正在执行 cURL POST 并返回错误响应,将其解析为数组,但现在 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>
// 函数/类
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;
}
}
//调用函数
// $errorMessage is holding the XML value in an array index
// something like: $arr[3] = $xml;
$errMsg = new parseXML($arr[3]);
$errMsgArr = $errMsg->getErrorMessage();
我想要的是所有的错误代码和描述属性值
编辑:
好的,这是 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.
)
)
)
)
对于我的一生,我无法弄清楚为什么我可以获得代码和描述,有什么想法吗?
编辑 #2 好的,我想我会分解它。
我正在使用 cURL 向我们的一台服务器发布请求,我解析出 HTTP 响应标头和 xml(如果返回了 xml)。 header/xml 中的每一行我都分解成一个数组。因此,如果出现错误,我会看到数组的额外索引。然后我做这样的事情。
$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).
之后我会这样做:
$errMsg = new parseXML($if_err_from_header);
$errMsgArr = $errMsg->getErrorMessage();
我仍然无法从错误的属性中获取代码和描述,我错过了什么?
编辑 #3 好的,为什么这行得通?
$in_arr = false;
// This returns all the code attributes
$el = $this->xml->xpath("//@code");
# if $el is false, nothing returned from xpath(), set to an empty array
$el = $el == false ? array() : $el;
foreach($el as $element) {
$in_arr[] = array("code" => $element["code"], "description" => $element["description"]);
}
return $in_arr;
编辑#4:
好的,这得到了我想要的值,但它有点像 hack,想选择特定的元素但是......
$el = $this->xml->xpath("//*");
【问题讨论】: