#php #json #xml
Вопрос:
Привет, у меня есть раздел XML-файла, который содержит
lt;Question type="2" text="Which one of the following area codes is associated with you?"gt; lt;Answer correct="false"gt;606lt;/Answergt; lt;Answer correct="false"gt;859lt;/Answergt; lt;Answer correct="false"gt;616lt;/Answergt; lt;Answer correct="false"gt;614/380lt;/Answergt; lt;Answer correct="false"gt;812lt;/Answergt; lt;Answer correct="true"gt;502lt;/Answergt; lt;Answer correct="false"gt;810lt;/Answergt; lt;Answer correct="false"gt;740lt;/Answergt; lt;Answer correct="false"gt;248lt;/Answergt; lt;Answer correct="false"gt;None of the abovelt;/Answergt; lt;/Questiongt;
Я использую это для анализа ответа
$objXmlDocument = simplexml_load_string($response,null,LIBXML_NOCDATA); if ($objXmlDocument === FALSE) { echo "There were errors parsing the XML file.n"; foreach(libxml_get_errors() as $error) { echo $error-gt;message; } exit; } $objJsonDocument = json_encode($objXmlDocument); $arrOutput = json_decode($objJsonDocument,TRUE);
Когда результаты возвращаются, я получаю тип вопроса, но не получаю правильное поле значения. Это из-за глубины структуры ?
Ответ №1:
Да, похоже, что только первый (конверт) получает свои атрибуты в массиве.
Вам нужно будет пройти через них.
Пример:
$response = 'lt;Question type="2" text="Which one of the following area codes is associated with you?"gt; lt;Answer correct="false"gt;606lt;/Answergt; lt;Answer correct="false"gt;859lt;/Answergt; lt;Answer correct="false"gt;616lt;/Answergt; lt;Answer correct="false"gt;614/380lt;/Answergt; lt;Answer correct="false"gt;812lt;/Answergt; lt;Answer correct="true"gt;502lt;/Answergt; lt;Answer correct="false"gt;810lt;/Answergt; lt;Answer correct="false"gt;740lt;/Answergt; lt;Answer correct="false"gt;248lt;/Answergt; lt;Answer correct="false"gt;None of the abovelt;/Answergt; lt;/Questiongt;'; $objXmlDocument = simplexml_load_string($response, null, LIBXML_NOCDATA); if ($objXmlDocument === false) { echo "There were errors parsing the XML file.n"; foreach (libxml_get_errors() as $error) { echo $error-gt;message; } exit; } $arrOutput = json_decode(json_encode($objXmlDocument), true); unset($arrOutput['Answer']); foreach ($objXmlDocument as $key =gt; $answer) { $arrOutput[$key][] = json_decode(json_encode($answer), true); } echo var_export($arrOutput, true) . PHP_EOL;
Выход:
[ '@attributes' =gt; [ 'type' =gt; '2', 'text' =gt; 'Which one of the following area codes is associated with you?', ], 'Answer' =gt; [ 0 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; '606', ], 1 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; '859', ], 2 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; '616', ], 3 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; '614/380', ], 4 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; '812', ], 5 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'true', ], 0 =gt; '502', ], 6 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; '810', ], 7 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; '740', ], 8 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; '248', ], 9 =gt; [ '@attributes' =gt; [ 'correct' =gt; 'false', ], 0 =gt; 'None of the above', ], ], ];
Теперь вам просто нужно разобраться, чего вы хотите от этих данных.
ПРАВКА: это не «элегантно». Возможно, вам просто следует использовать метод get атрибута ect для создания массива того, что вам нужно.
Ответ №2:
Хорошо, избегайте маршрута json_decode. Слишком много работы. Вот элегантный способ — чистый аккуратный код, который легко понять.
lt;?php $xmlstring = 'lt;Question type="2" text="Which one of the following area codes is associated with you?"gt; lt;Answer correct="false"gt;606lt;/Answergt; lt;Answer correct="false"gt;859lt;/Answergt; lt;Answer correct="false"gt;616lt;/Answergt; lt;Answer correct="false"gt;614/380lt;/Answergt; lt;Answer correct="false"gt;812lt;/Answergt; lt;Answer correct="true"gt;502lt;/Answergt; lt;Answer correct="false"gt;810lt;/Answergt; lt;Answer correct="false"gt;740lt;/Answergt; lt;Answer correct="false"gt;248lt;/Answergt; lt;Answer correct="false"gt;None of the abovelt;/Answergt; lt;/Questiongt;'; $initialize = new SimpleXMLElement($xmlstring); //extract the attributes text and type below $accessQuestionText = $initialize-gt;attributes()-gt;text; $accessQuestionType = $initialize-gt;attributes()-gt;type; //using for each loop lets iterate over the Possible Answers foreach($initialize-gt;Answer as $answers){ echo "Question of Type $accessQuestionType is $accessQuestionText "; echo "The List of Dropdown answers can be ".$answers."lt;brgt;"; }
Вывод выглядит так: