0
我有下面的XML $結果循環通過PHP xml_parser,變成陣列,以供參考
<Response>
[.....]
<Questions>
<Question type="1" text="Which one of their favorite color?">
<Answer correct="false">RED</Answer>
<Answer correct="false">BLUE</Answer>
<Answer correct="true">BLACK</Answer>
<Answer correct="false">YELLOW</Answer>
</Question>
<Question type="2" text="What is their favorite food?">
<Answer correct="false">PIZZA</Answer>
<Answer correct="false">TACOS</Answer>
<Answer correct="true">CAKE</Answer>
<Answer correct="false">CHEESE</Answer>
</Question>
<Question type="3" text="Which person do they hate the most?">
<Answer correct="false">Bill</Answer>
<Answer correct="true">Jack</Answer>
<Answer correct="false">Jammie</Answer>
<Answer correct="false">Rick</Answer>
</Question>
</Questions>
</Response>
我知道我會想使用...
$xml = simplexml_load_string($result);
這將設置$ XML到SimpleXML對象的結果。我想知道最好的方法來循環這些問題的文本,所以我可以把所有的問題,並將它們添加到一個數組,然後通過類型#,問題文本和答案很容易引用他們,所以我可以做
$QuestionText = $array["1"]["text"] //Which one is their favorite color?
$QuestionAnswer = $array["1"]["answer"] //BLACK
編輯#1
雖然我還沒有回一個響應但我一直在試圖找出自己,我已經改變了我的方法的xml_parser ...
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
xml_parse_into_struct($xml_parser, $result, $vals,$index);
xml_parser_free($xml_parser);
$newResArr = array();
foreach($vals as $val)
{
if(($val['tag']=='Question')) {
if(isset($val['attributes'])){
$type = $val['attributes']['type'];
$newResArr[$type]['text'] = $val['attributes']['text'];
//I assume a foreach needs to be put here?
}
}
}
現在我可以通過執行$ newRes來引用文本Arr ['1'] ['text']我得到了我想要的,但是我不知道如何設置foreach循環,如上所述,如果它的屬性設置爲true,就拉取答案。
你真的想轉換並以數組的方式訪問它嗎? –
大聲笑,是的,這就是爲什麼我想這樣做:) – eqiz
因爲simplexml_load_string返回一個對象,你可以訪問對象,雖然它不是一個數組 –