簡體   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