Pop\Data\Type\Xml::decode PHP Метод

decode() публичный статический Метод

Decode the data into PHP.
public static decode ( string $data, boolean $preserve = false ) : mixed
$data string
$preserve boolean
Результат mixed
    public static function decode($data, $preserve = false)
    {
        $nodes = array();
        if ($preserve) {
            $matches = array();
            preg_match_all('/<!\\[cdata\\[(.*?)\\]\\]>/is', $data, $matches);
            foreach ($matches[0] as $match) {
                $strip = str_replace(array('<![CDATA[', ']]>', '<', '>'), array('', '', '&lt;', '&gt;'), $match);
                $data = str_replace($match, $strip, $data);
            }
            $nodes = json_decode(json_encode((array) simplexml_load_string($data)), true);
        } else {
            $xml = new \SimpleXMLElement($data);
            $i = 1;
            foreach ($xml as $key => $node) {
                $objs = array();
                foreach ($node as $k => $v) {
                    $j = 1;
                    if (array_key_exists((string) $k, $objs)) {
                        while (array_key_exists($k . '_' . $j, $objs)) {
                            $j++;
                        }
                        $newKey = (string) $k . '_' . $j;
                    } else {
                        $newKey = (string) $k;
                    }
                    $objs[$newKey] = trim((string) $v);
                }
                $nodes[$key . '_' . $i] = $objs;
                $i++;
            }
        }
        return $nodes;
    }

Usage Example

Пример #1
0
    public function testDecodePreserve()
    {
        $xml = <<<XML
<users>
    <row>
        <username>Test1</username>
        <password>123456</password>
        <email>[email protected]</email>
    </row>
    <row>
        <username>Test2</username>
        <password>123456</password>
        <email>[email protected]</email>
    </row>
</users>
XML;
        $x = Xml::decode($xml, true);
        $this->assertEquals(2, count($x['row']));
        $this->assertEquals('Test1', $x['row'][0]['username']);
    }