2016-09-23 9 views
0

PHPを使用して別のノード値に従ってXML内の特定のノードを取得する方法は?私は、このサンプルのようなXMLで動作するようにしようとしています

<?xml version="1.0"?> 
<quizReport version="1" xsi:schemaLocation="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults quizReport.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults"> 
<quizSettings timeLimit="0" maxNormalizedScore="100" maxScore="20" quizType="graded"> 

<passingPercent>0.6</passingPercent> 
</quizSettings> 
<summary time="4" percent="0.5" score="10"> 
<variables> 
    <variable title="Nom" value="test1411" name="USER_NAME"/> 

    <variable title="Courriel" value="" name="USER_EMAIL"/> 
</variables> 
</summary> 


<questions> 
<trueFalseQuestion usedAttempts="1" awardedPoints="10" maxAttempts="1" maxPoints="10" status="correct" id="{11AD6662-ACF3-4C2B-A3E6-04311C0DD8DB}"> 
<direction>Le mot de passe de votre compte iNews est indépendant de votre mot de passe radiocanadien géré par ActiveDirectory. </direction> 
<answers userAnswerIndex="0" correctAnswerIndex="0"> 
<answer>Vrai </answer> 
<answer>Faux </answer> 
</answers> 
</trueFalseQuestion> 

<trueFalseQuestion usedAttempts="1" awardedPoints="0" maxAttempts="1" maxPoints="10" status="incorrect" id="{F13CF7F1-C830-41AF-A54C-CE78EE383611}"> 
<direction>Le protocole FTP permet de reprendre un transfert de fichier qui a été arrêté, sans recommencer le transfert depuis le début. </direction> 
<answers userAnswerIndex="1" correctAnswerIndex="0"> 
<answer>Vrai </answer> 
<answer>Faux </answer> 
</answers> 
</trueFalseQuestion> 
</questions> 
</quizReport> 

それぞれの質問には、例えば、ID属性を持っています{11AD6662-ACF3-4C2B-A3E6-04311C0DD8DB}。 質問のステータスがテキストとして返されます(つまり、が正しいまたはが正しくありません。)。

私の目標は、各質問のステータスを抽出し、同じ質問IDで列がラベル付けされているデータベースに入れます(私はMySQL INSERTに慣れています)。

私は多くのソリューション(xPath、foreach ...)を試しましたが、動作するコードを取得できません。すべての努力は、SimpleXMLElementを使用して行われました。

したがって、終了時に、私は質問IDで標識された列の下正しい又は誤っ DBに値を挿入する(例えば、{11AD6662-ACF3-4C2B-A3E6-04311C0DD8DB})毎XMLの1つの質問(最大100の質問を含むことができる)。だからXMLを介していくつかの種類のループが必要です。

タグ名truFalseQuestionは、質問のタイプによって異なる場合があります(別の質問が複数の選択肢があるなど)。私はこの単純なXMLをステップバイステップで理解できるようにしました。

+0

* {11AD6662-ACF3-4C2B-A3E6-04311C0DD8DB}というラベルの列の下に* ... MySQLがそのようなフィールド名を許可するのではないかと疑います。あなたはおそらく* questionid *とこれを値として別のフィールドを意味していました。 – Parfait

+1

このアプローチでは、可能性のある質問タグ名を一覧表示するためにメタデータを追加する必要があるようです。 – bassxzero

答えて

0

PHP SimpleXML libraryを使用すると、xmlの解析を処理できます。例えば:あなたのデータと

//presuming that xml data is stored in $xmlContents 
$xmlData = new SimpleXMLElement($xmlContents); 
$keys = get_object_vars($xmlData); 
$aValues = array(); 
foreach($keys as $key=>$property) { 
    if (stripos($key,'questions')!== false) {  
     foreach($property as $questionType=>$question) { 
      $aValues[] = "('".(string)$question['id']."','".(string)$question['status']."')"; 
     } 
    } 
} 
if (count($aValues)) { 
    //presumed table and columns - modify per your names - this is a sample SQL statement - if you are using a different database variant, modify accordingly 
    $query = 'INSERT INTO questionStatus (questionId,status) VALUES ' .  implode(',',$aValues); 
    print($query); 
    //@TODO: run insert statement with your database layer code 
} 

出力:

INSERT INTO questionStatus (questionId,status) VALUES ('{11AD6662-ACF3-4C2B-A3E6-04311C0DD8DB}','correct'),('{F13CF7F1-C830-41AF-A54C-CE78EE383611}','incorrect') 
+0

これはどのようにして異なる質問タイプの問題を解決しますか? – bassxzero

+0

実際、OPは* multipleChoiceQuestion *を誰が何人知っているかの潜在的な要素として言及しています!上記の@ bassxzeroのコメントからの返答を待つべきです。 – Parfait

+0

ええ、私たちは['get_object_vars()'](http://php.net/manual/en/function.get-object-vars)を使うことができます。php)を使って 'questions'を含むプロパティを見つけてください。うまくいけば十分でしょうか? –

0

は、あなたが質問要素のすべての子ノードを実行することができます。

各子ノードのタグ名は、getName()関数を使用して見つけることができます。

ここにいくつかのサンプルコードがあります。私はそれがアイデアを得るのを助けることを願っています。

<?php 
//if your XML is stored in a file named "test.xml", you can load it from there. 
//Otherwise try simplexml_load_string($xmlstring) 
$file=simplexml_load_file("test.xml"); 

//get the questions 
$questions=$file->questions->children(); 
foreach($questions as $question) { 

    //as a sample there is some data printed for each question. 
    print "QuestionType: ". $question->getName()."\n"; 
    print "QuestionID: ". $question->attributes()->id."\n"; 
    print "Direction: ".(string) $question->direction."\n"; 
    print "\n"; 
    print "Answers: \n"; 
    foreach($question->answers->answer as $answer){ 
     print (string)$answer."\n"; 
    } 

    print "\n\n"; 
} 

[EDIT]

それはこのようなものを印刷:

 
QuestionType: trueFalseQuestion 
QuestionID: {11AD6662-ACF3-4C2B-A3E6-04311C0DD8DB} 
Direction: Le mot de passe de votre compte iNews est indépendant de votre mot de passe radiocanadien géré par ActiveDirectory. 

Answers: 
Vrai 
Faux 


QuestionType: trueFalseQuestion 
QuestionID: {F13CF7F1-C830-41AF-A54C-CE78EE383611} 
Direction: Le protocole FTP permet de reprendre un transfert de fichier qui a été arrêté, sans recommencer le transfert depuis le début. 

Answers: 
Vrai 
Faux 

[/ EDIT]

EDIT2:追加のサンプルコードとサンプル出力するID

+0

スタックオーバーフローでは、すべての投稿の改訂履歴が実際に格納されます。したがって、投稿後に編集内容に何かを追加したことを示す必要はありません。編集した内容は誰でも「編集したX秒/分/時/日/その他」をクリックして見ることができます。テキスト。 – dorukayhan

+0

ありがとう!私はまだこれを見ていない。 – akrys

+0

私のコードを '$ xmlData = new SimpleXMLElement($ fichierxml)に変更しました。 foreach($ xmlData-> questions-> trueFalseQuestion $ question){ $ questionid =(string)$ question ['id']; $ questionstatus =(文字列)$ question ['status']; \t $ sql = "INSERT INTO test_xml_questions($ questionid) VALUES( '$ questionstatus')"; } 'と表示されますが、DBには何も挿入されません... ** {11AD6662-ACF3-4C2B-A3E6-04311C0DD8DB} **および** {F13CF7F1-C830-41AF-A54C-CE78EE383611} **と表示されます。賞賛は違法な文字ですか? – Clitorio

関連する問題