0

我试图在 XML 解析期间从几个相互关联的函数中获取变量并将它们放入数组中。代码是:

function readChapters($reader) {
    while($reader->read()) {
        if( /* condition here */ ) {
            $chapter = readValue($reader);
        }
        if( /* condition here */ ) {
            readModules($reader);
        }
        if( /* condition here */ ) {
            return;
        }
    }
}

function readModules($reader) {
    while($reader->read()) {
        if( /* condition here */ ) {
            readModule($reader);
        }
        if( /* condition here */ ) {
            return($reader);
        }
    }
}

function readModule($reader) {
    while($reader->read()) {
        if( /* condition here */ ) {
            $topic = readValue($reader);
        }
        if( /* condition here */ ) {
            $description = readValue($reader);
        }
    }
}

function readValue($reader) {
    while($reader->read()) {
        if( /* condition here */ ) {
            return $reader->readInnerXML();
        }
    }
}

$reader = new XMLReader();
$reader->open('example.xml');

$current = 0;
$topics_list = array();

$chapterName = "";          // want to add $chapter
$topicName = "";            // want to add $topic
$descriptionText = "";      // want to add $description

while($reader->read()) {
    if(// condition here) {
        readChapters($reader);
    }
    $topics_list[$current] = array();
    $topics_list[$current]['chapter'] = $chapterName;
    $topics_list[$current]['topic'] = $topicName;
    $topics_list[$current]['description'] = $descriptionText;
}
$reader->close();
print_r($topics_list);

问题:如何从这些函数之外获取$chapter$topic$description变量以便将它们放入数组中?提前致谢。

更新: XML 文档结构在这里,以及 Array() 的预期结构:

Array (
            [0] => Array (
                    [chapter] => Chapter_name1
                    [topic] => Topic_name1
                    [description] => Content_of_the_topic1
                )
            [1] => Array (
                    [chapter] => Chapter_name1
                    [topic] => Topic_name2
                    [description] => Content_of_the_topic2
                )
            [2] => Array (
                    [chapter] => Chapter_name2
                    [topic] => Topic_name2
                    [description] => Content_of_the_topic2
            )
            .....
        )
4

1 回答 1

0

您实际上是在使用一组函数来使用来自 XML 对象的数据来构建数据结构。这意味着每个函数都应该返回它命名的数据结构:readChapters() 应该返回一个章节结构(并且可能应该命名为 readChapter(),因为我认为它只阅读一章,对吗?),等等。我不知道你的 XML 是什么样的,或者你想要的数据结构是什么样的,但你会想要这样的东西:

function readChapter($reader) {
    $chapter = array();
    while (// condition) {
         if (// something)
              $chapter['chapter'] = readValue($reader);
         elseif (// something else)
              $chapter['topic'] = readValue($reader);
         // etc
    }

    return $chapter;
}

然后在你下面的主循环中,你可以有这个:

while ($reader->read()) {
    if (// condition here) {
        $topics_list[] = readChapter($reader);
    }
}

希望这能让你更接近你可以建造的东西!

于 2013-01-26T17:56:04.243 回答