【发布时间】:2021-12-13 07:24:08
【问题描述】:
您好,我在从 XML 输出中提取数据时遇到问题。 XML如下...
<Question type="5" text="What state was your SSN issued in?">
<Answer correct="false">Maryland</Answer>
<Answer correct="false">Alaska</Answer>
<Answer correct="false">Ohio</Answer>
<Answer correct="false">Indiana</Answer>
<Answer correct="false">Missouri</Answer>
<Answer correct="false">Washington</Answer>
<Answer correct="false">Arkansas</Answer>
<Answer correct="false">Illinois</Answer>
<Answer correct="true">Kentucky</Answer>
<Answer correct="false">None of the above</Answer>
</Question>
我的挑战是当我使用这段代码时
$ch = curl_init($serviceUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// Debug output of the response
libxml_use_internal_errors(TRUE);
$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->message;
}
exit;
}
$objJsonDocument = json_encode($objXmlDocument);
$arrOutput = json_decode($objJsonDocument,true);
我可以将数据提取为一个数组,除了一个例外,一切正常。正确的属性从结果数组中脱落。并且无法调用。
似乎该数组将采用问题属性类型和文本,但由于它是它的子级别,因此它不会拾取正确的属性。
我的 XML/Json 知识还可以,但这个让我很难过。任何想法都会很棒。
这就是我为项目其他部分解析数据的方式
$question_1 = $arrOutput['Response']['Questions']['Question']['0']['@attributes']['text'];
$answer_choices_one = $arrOutput['Response']['Questions']['Question'][0]['Answer'];
我希望当我使用 foreach 循环构建问题选择以获取正确的属性并将其存储在我正在使用的输入字段的值字段中...我似乎无法获得该死的价值。
感谢您的见解。
【问题讨论】:
标签: php arrays json xml attributes