繁体   English   中英

从多级 XML 结果 (API) 中提取 CDATA 时遇到问题

[英]Trouble Extracting CDATA from Multi Level XML Result (API)

嗨,我在从 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 循环来构建问题选择以获取正确的属性并将其存储在我正在使用的输入字段的值字段中时......我似乎无法获得该死的值。

感谢您的见解。

下面的代码不仅提取了可能的答案列表,而且还显示了问题、其类型和从 API 返回的可能答案。

    <?php

$xmlstring = '<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>';

$initialize = new SimpleXMLElement($xmlstring);

//extract the attributes text and type below
$accessQuestionText = $initialize->attributes()->text;
$accessQuestionType = $initialize->attributes()->type;

//using for each loop lets iterate over the Possible Answers
foreach($initialize->Answer as $answers){

    echo "Question of Type $accessQuestionType is $accessQuestionText ";
    echo "The List of Dropdown answers can be ".$answers."<br>";
}

输出如下; 在此处输入图片说明

希望这对你有很大帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM