我试图在 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
)
.....
)