перебор неизвестной структуры XML с помощью PHP (DOM) - PullRequest
6 голосов
/ 17 июня 2009

Я хочу написать функцию, которая анализирует (теоретически) неизвестную структуру данных XML в эквивалентный массив PHP.

Вот мой пример XML:

<?xml version="1.0" encoding="UTF-8"?>
<content>

<title>Sample Text</title>

<introduction>
    <paragraph>This is some rudimentary text</paragraph>
</introduction>
<description>
    <paragraph>Here is some more text</paragraph>
    <paragraph>Even MORE text</paragraph>
    <sub_section>
        <sub_para>This is a smaller, sub paragraph</sub_para>
        <sub_para>This is another smaller, sub paragraph</sub_para>
    </sub_section>
</description>
</content>

Я изменил эту итеративную функцию DOM из devarticles:

$data = 'path/to/xmldoc.xml';
$xmlDoc = new DOMDocument(); #create a DOM element
$xmlDoc->load( $data ); #load data into the element
$xmlRoot = $xmlDoc->firstChild; #establish root

function xml2array($node)
    {
    if ($node->hasChildNodes())
    {
$subNodes = $node->childNodes;
    foreach ($subNodes as $subNode)
        {
        #filter node types
        if (($subNode->nodeType != 3) || (($subNode->nodeType == 3)))   
            {
            $arraydata[$subNode->nodeName]=$subNode->nodeValue;
            }
         xml2array($subNode);
         }
      }
      return $arraydata;
   }
//The getNodesInfo function call

 $xmlarray = xml2array($xmlRoot);


// print the output - with a little bit of formatting for ease of use...
foreach($xmlarray as $xkey)
     {
     echo"$xkey<br/><br/>";
     }

Теперь, из-за того, как я передаю элементы в массив, я перезаписываю любые элементы, которые имеют общее имя узла (поскольку в идеале я хочу дать ключам то же имя, что и их исходным узлам). Моя рекурсия не велика ... Однако, даже если я опущу квадратные скобки - второй уровень узлов все еще входит как значения на первом уровне (см. Текст описания узла).

У кого-нибудь есть идеи, как мне лучше построить это?

Ответы [ 3 ]

2 голосов
/ 17 июня 2009

Вам может быть лучше, просто вытащив какой-то код из сети

http://www.bin -co.com / PHP / скрипты / xml2array /

    /**
     * xml2array() will convert the given XML text to an array in the XML structure.
     * Link: http://www.bin-co.com/php/scripts/xml2array/
     * Arguments : $contents - The XML text
     *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
     *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
     * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
     * Examples: $array =  xml2array(file_get_contents('feed.xml'));
     *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute'));
     */
    function xml2array($contents, $get_attributes=1, $priority = 'tag') { 
1 голос
/ 17 июня 2009

Вас могут заинтересовать SimpleXML или xml_parse_into_struct .

$ arraydata не передается в последующие вызовы xml2array () и не используется возвращаемое значение, поэтому да «Моя рекурсия не велика ...» - это правда; Чтобы добавить новый элемент в существующий массив, вы можете использовать пустые квадратные скобки, $ arr [] = 123; $ arr [$ x] [] = 123;

0 голосов
/ 17 июня 2009

Вы также можете проверить XML Unserializer

http://pear.php.net/package/XML_Serializer/redirected

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...