php xpath problems

Posted by Phill Pafford on Stack Overflow See other posts from Stack Overflow or by Phill Pafford
Published on 2010-05-18T20:12:17Z Indexed on 2010/05/18 20:20 UTC
Read the original article Hit count: 459

Filed under:
|
|
|

I'm doing a cURL POST and get the error response back, parse it into an array but having issues with xpath now.

// 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;
    }
}

// Calling function

// $errorMessage is holding the XML value in an array index
// something like: $arr[3] = $xml;
$errMsg = new parseXML($arr[3]); 
$errMsgArr = $errMsg->getErrorMessage();

What I would like is all the error code and description attribute values

© Stack Overflow or respective owner

Related posts about php

Related posts about Xml