问题:
我有一个包含13个xml文件的zip文件。除第一个文件外,每个文件都包含一个测验问题和几个答案。当我将文件上传到下面的脚本时,它会正确地打印出问题和答案,但不是按顺序。每次上传zip文件时,问题的顺序都会随机移动。
问题:
有没有办法可以利用文件名告诉脚本每次都按顺序打印问题?
Zip文件包含:
PHP脚本(警告,长脚本):
<?php
//Initialize counter
$i = 0;
//Go through each file
while (($file = readdir($dh)) !== false)
{
//Skipt the first loop
if ($i > 1)
{
//Ignore misc file
if ($file != 'imsmanifest.xml')
{
//Create new DOM document
$dom= new DOMDocument();
//Load XML file
$dom->load('uploads/' . $file);
//Do not preserve white space
$dom->preserveWhiteSpace = false;
//Check if correct answers should be displayed
if (isset($_POST['XMLAnswers']))
{
//Get correct answer
$correct = $dom->getElementsByTagName( "correctResponse" )->item(0)->nodeValue;
//Get question
$questions = $dom->getElementsByTagName('p')->item(0)->nodeValue;
//Print out question
echo '<h4>' . htmlspecialchars($questions) . '</h4>' . "\n";
//Get answers
$domTable = $dom->getElementsByTagName("simpleChoice");
//Loop through each answer
foreach ($domTable as $answers)
{
//Delete potential unnecessary tags
$pattern = array(
'<p xmlns="http://www.imsglobal.org/xsd/imsqti_v2p1">',
'</p>'
);
//Check if answer is correct one
if ($correct == $answers->getAttribute('identifier'))
{
//Print out correct answer
echo '<span style="color:red;">' . utf8_decode(str_replace($pattern, '', innerHTML($answers))) . '</span><br />' . "\n";
}
else
{
//Print out answer
echo utf8_decode(str_replace($pattern, '', innerHTML($answers))) . '<br />' . "\n";
}
}
}
}
}
//Increment counter
$i++;
}
?>
答案 0 :(得分:2)
使用scandir而不是使用opendir / readdir。见http://www.php.net/manual/en/function.scandir.php。 scandir返回目录中已排序的文件数组。除了用readdir循环替换外部时,您应该能够放入此代码并让代码以最小的更改工作:
$files = scandir($dir);
foreach ($files as $file) {
//your current code
}