我们有一个这种格式的XML文件:
<Quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<id>0</id>
<title>Ganz Anderer Titel</title>
<questions>
<Question xsi:type="ChoiceQuestion">
<title>Frage1</title>
<id>0</id>
<rightAnswer>1</rightAnswer>
</Question>
<Question xsi:type="ChoiceQuestion">
<title>Frage2</title>
<id>1</id>
<rightAnswer>2</rightAnswer>
</Question>
<Question xsi:type="ChoiceQuestion">
<title>Frage2</title>
<id>2</id>
<rightAnswer>3</rightAnswer>
</Question>
</questions>
<expireDate>2018-06-06T00:00:00</expireDate>
</Quiz>
我们现在需要解析这个XML文件,但是我们无法访问questions元素的内容或属性。
我们正在使用PHP 7和内置的SimpleXML解析器。
echo json_encode($xml->questions);
显示此
{"Question":[{"title":"Frage1","id":"0","rightAnswer":"1"},{"title":"Frage2","id":"1","rightAnswer":"2"},{"title":"Frage2","id":"2","rightAnswer":"3"}]}
但我们不知道如何单独获取每个问题的数据。
答案 0 :(得分:0)
正如评论中所建议的那样,一个简单的foreach
循环将让您遍历列表中的每个项目。要获取命名空间属性,请使用SimpleXMLElement::attributes()
方法:
$xml = <<< XML
<Quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<id>0</id>
<title>Ganz Anderer Titel</title>
<questions>
<Question xsi:type="ChoiceQuestion">
<title>Frage1</title>
<id>0</id>
<rightAnswer>1</rightAnswer>
</Question>
<Question xsi:type="ChoiceQuestion">
<title>Frage2</title>
<id>1</id>
<rightAnswer>2</rightAnswer>
</Question>
<Question xsi:type="ChoiceQuestion">
<title>Frage2</title>
<id>2</id>
<rightAnswer>3</rightAnswer>
</Question>
</questions>
<expireDate>2018-06-06T00:00:00</expireDate>
</Quiz>
XML;
$x = new SimpleXMLElement($xml);
foreach ($x->questions->Question as $q) {
printf(
"Question %d:\nType:%s\nTitle:%s\nRight answer:%s\n",
$q->id,
$q->attributes("xsi", true)->type,
$q->title,
$q->rightAnswer
);
}