php simpleXMLElement to array: null value

后端 未结 3 1782
南方客
南方客 2021-02-14 13:49

I\'ve got following XML:


    123
    
    ACTIVE

         


        
3条回答
  •  既然无缘
    2021-02-14 14:37

    An empty SimpleXMLElement object will be casted to an empty array. You can change this by by extending from SimpleXMLElement and implementing the JsonSerializable interface and casting an it to null.

    /**
     * Class JsonXMLElement
     */
    class JsonXMLElement extends SimpleXMLElement implements JsonSerializable
    {
    
        /**
         * Specify data which should be serialized to JSON
         *
         * @return mixed data which can be serialized by json_encode.
         */
        public function jsonSerialize()
        {
            $array = array();
    
            // json encode attributes if any.
            if ($attributes = $this->attributes()) {
                $array['@attributes'] = iterator_to_array($attributes);
            }
    
            // json encode child elements if any. group on duplicate names as an array.
            foreach ($this as $name => $element) {
                if (isset($array[$name])) {
                    if (!is_array($array[$name])) {
                        $array[$name] = [$array[$name]];
                    }
                    $array[$name][] = $element;
                } else {
                    $array[$name] = $element;
                }
            }
    
            // json encode non-whitespace element simplexml text values.
            $text = trim($this);
            if (strlen($text)) {
                if ($array) {
                    $array['@text'] = $text;
                } else {
                    $array = $text;
                }
            }
    
            // return empty elements as NULL (self-closing or empty tags)
            if (!$array) {
                $array = NULL;
            }
    
            return $array;
        }
    }
    

    Then tell simplexml_load_string to return an object of JsonXMLElement class

    $xml = <<
       123
       
       ACTIVE
    
    XML;
    
    $obj = simplexml_load_string($xml, 'JsonXMLElement');
    
    // print_r($obj);
    
    print json_encode($obj, true);
    
    /*
     * Output...
    {
       "id": 123,
       "email": null,
       "status": "ACTIVE"
    }
    */
    

    Credit: hakre

提交回复
热议问题