XeroPHP\Helpers::XMLToArray PHP Method

XMLToArray() public static method

public static XMLToArray ( SimpleXMLElement $sxml )
$sxml SimpleXMLElement
    public static function XMLToArray(\SimpleXMLElement $sxml)
    {
        $output = [];
        $singular_node_name = self::singularize($sxml->getName());
        foreach ($sxml->children() as $child_name => $child) {
            /**
             * @var \SimpleXMLElement $child
             */
            if ($child->count() > 0) {
                $node = self::XMLToArray($child);
            } else {
                $node = (string) $child;
            }
            //don't make it assoc, as the keys will all be the same
            if ($child_name === $singular_node_name) {
                $output[] = $node;
            } else {
                $output[$child_name] = $node;
            }
        }
        return $output;
    }

Usage Example

示例#1
0
 public function parseXML()
 {
     $sxml = new SimpleXMLElement($this->response_body);
     // For lack of a better way to find the elements returned (every time)
     // XML has an array 2 levels deep due to its non-unique key nature.
     /** @var SimpleXMLElement $root_child */
     foreach ($sxml as $child_index => $root_child) {
         switch ($child_index) {
             case 'ErrorNumber':
                 $this->root_error['code'] = (string) $root_child;
                 break;
             case 'Type':
                 $this->root_error['type'] = (string) $root_child;
                 break;
             case 'Message':
                 $this->root_error['message'] = (string) $root_child;
                 break;
             case 'Payslip':
             case 'PayItems':
                 // some xero endpoints are 1D so we can parse them straight away
                 $this->elements[] = Helpers::XMLToArray($root_child);
                 break;
             default:
                 //Happy to make the assumption that there will only be one
                 //root node with > than 2D children.
                 foreach ($root_child->children() as $element_index => $element) {
                     $this->elements[] = Helpers::XMLToArray($element);
                 }
         }
     }
 }