我正在尝试在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文档结构为here,以及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
)
.....
)
答案 0 :(得分: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);
}
}
希望能让你更接近你可以建立的东西!