Извлечение данных XML, когда имена дочерних узлов неизвестны

У меня есть система тестов от iSpring Solutions, которая отправляет данные результатов XML в мой скрипт php. Я хочу извлечь информацию для обновления базы данных MySQL.

Каждый тест имеет разные вопросы, поэтому XML-файл не всегда имеет одинаковую длину / структуру, однако мне нужно получить конкретные данные.

Вот выдержка из XML-файла

<questions>

<matchingQuestion id="{3F033905-566A-4B67-B7E4-324E4367FD16}" status="correct" maxPoints="2" maxAttempts="1" awardedPoints="2" usedAttempts="1">
<direction>Match the items on the left with the items on the right</direction>
</matchingQuestion>

<fillInTheBlankQuestionEx id="{6FCC5DAC-168F-4F44-87DF-9B1D162268D1}" status="partially" maxPoints="8" maxAttempts="1" awardedPoints="4" usedAttempts="1">
<direction>Which indefinite article should be written in front of the following words - 'a' or 'an'?</direction>
</fillInTheBlankQuestionEx>

</questions>

Мне необходимо
(а) получить имя / идентификатор каждого дочернего узла
(б) получить идентификатор, статус, значения maxPoints
(c) затем получите значение ‘direction’

Имя узла «MatchQuestion» или «FillInTheBlankQuestionEx» всегда меняет порядок в зависимости от викторины.

Я не могу понять, как получить эти значения, так как типы вопросов варьируются для каждого теста!

Спасибо заранее

Джон

Полный XML-файл:

    <quizReport xsi:schemaLocation="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults quizReport.xsd" version="1" xmlns="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<quizSettings quizType="graded" maxScore="10" maxNormalizedScore="100" timeLimit="180">
<passingPercent>0.8</passingPercent>
</quizSettings>
<summary score="2" percent="0.2" time="6">
<variables>
<variable name="VARIABLE_2" title="DFE number (7 digit)" value="2112377"/>
<variable name="USER_NAME" title="Your name" value="John"/>
<variable name="VARIABLE_1" title="Your class" value="6M"/>
</variables>
</summary>
<questions>
<matchingQuestion id="{3F033905-566A-4B67-B7E4-324E4367FD16}" status="correct" maxPoints="2" maxAttempts="1" awardedPoints="2" usedAttempts="1">
<direction>Match the items on the left with the items on the right</direction>
<premises>
<premise>an</premise>
<premise>a</premise>
</premises>
<responses>
<response>elephant</response>
<response>house</response>
</responses>
<matches>
<match premiseIndex="0" responseIndex="0"/>
<match premiseIndex="1" responseIndex="1"/>
</matches>
<userAnswer>
<match premiseIndex="0" responseIndex="0"/>
<match premiseIndex="1" responseIndex="1"/>
</userAnswer>
</matchingQuestion>
<fillInTheBlankQuestionEx id="{6FCC5DAC-168F-4F44-87DF-9B1D162268D1}" status="incorrect" maxPoints="8" maxAttempts="1" awardedPoints="0" usedAttempts="1">
<direction>Which indefinite article should be written in front of the following words - 'a' or 'an'?</direction>
<details>
<blank userAnswer="" correct="false">
<answer>a</answer>
<answer>a</answer>
</blank>
<text><![CDATA[ television
]]></text>
<blank userAnswer="" correct="false">
<answer>a</answer>
</blank>
<text><![CDATA[ boy
]]></text>
<blank userAnswer="" correct="false">
<answer>an</answer>
</blank>
<text><![CDATA[ umbrella
]]></text>
<blank userAnswer="" correct="false">
<answer>a</answer>
</blank>
<text><![CDATA[ house
]]></text>
<blank userAnswer="" correct="false">
<answer>an</answer>
</blank>
<text><![CDATA[ hour
]]></text>
<blank userAnswer="" correct="false">
<answer>an</answer>
</blank>
<text><![CDATA[ igloo
]]></text>
<blank userAnswer="" correct="false">
<answer>a</answer>
</blank>
<text><![CDATA[ minute
]]></text>
<blank userAnswer="" correct="false">
<answer>an</answer>
</blank>
<text><![CDATA[ elephant]]></text>
</details>
</fillInTheBlankQuestionEx>
</questions>
</quizReport>

1

Решение

Чтобы начать кодирование, я покажу пример. Предположим, $ text содержит xml

$xml = new SimpleXMLElement($text);
echo '<pre>';
foreach ($xml->questions->children() as $q) {
//      print_r($q); echo '<br/>';
print_r((string)$q->getName());echo '<br/>';
print_r((string)$q->attributes()->id);echo '<br/>';
print_r((string)$q->direction);echo '<br/>';
}

результат:

matchingQuestion
{3F033905-566A-4B67-B7E4-324E4367FD16}
Match the items on the left with the items on the right
fillInTheBlankQuestionEx
{6FCC5DAC-168F-4F44-87DF-9B1D162268D1}
Which indefinite article should be written in front of the following words - 'a' or 'an'?
0

Другие решения

Спасибо за ваш ответ, я использовал приведенный ниже код из Splash58, чтобы переписать php, который обновляет базу данных mysql:

    foreach ($xml->questions->children() as $q) {
$QuestionType=(string)$q->getName();
$QuestionUUID=(string)$q->attributes()->id;
$QuestionAsked=(string)$q->direction;

$query="INSERT INTO questions (UUID, Qtype, Question) VALUES ('".$QuestionUUID."', '".$QuestionType."', '".$QuestionAsked."')";
$mysqli->query($query);

}

Однако в БД добавляется только первый вопрос.

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector