Перевод XML в массив

Советы и скрипты PHP
Ответить
Аватара пользователя
ukhov
Модератор
Модератор
Сообщения: 1343
Зарегистрирован: 04 янв 2011, 21:19

Перевод XML в массив

Сообщение ukhov »

XML → Array
Переводит XML-данные в массив (array).
Функция

Код: Выделить всё

<?phpfunction xml_decode($XML){    // Clean up white space    $XML = trim($XML);    $returnVal = $XML; // Default if just text;     // Expand empty tags    $emptyTag = '<(.*)/>';    $fullTag = '<\\1></\\1>';    $XML = preg_replace ("|$emptyTag|", $fullTag, $XML);     $matches = array();    if (preg_match_all('|<(.*)>(.*)</\\1>|Ums', trim($XML), $matches))    {        if (count($matches[1]) > 0) $returnVal = array(); // If we have matches then return an array else just text        foreach ($matches[1] as $index => $outerXML)        {            $attribute = $outerXML;            $value = xml_decode($matches[2][$index]);            if (! isset($returnVal[$attribute])) $returnVal[$attribute] = array();                $returnVal[$attribute][] = $value;        }    }    // Bring un-indexed singular arrays to a non-array value.    if (is_array($returnVal)) foreach ($returnVal as $key => $value)    {        if (is_array($value) && count($value) == 1 && key($value) === 0)        {            $returnVal[$key] = $returnVal[$key][0];        }    }    return $returnVal;}?>
Пример

Код: Выделить всё

<?php$xml_code = '<?xml version="1.0" encoding="windows-1251"?><data><name>TEST</name><site>flapps.ru</site></data>';$array = xml_decode($xml_code);print_r($array);?>
Ответить