2013-07-04 28 views
1

我正在製作一個測驗腳本。我想要一個「老師」來編輯問題。最初,我試圖使用mySQL,但它有點困難,所以我決定切換到JSON文件。PHP將JSON對象轉換爲字符串

做一些基本檢查用PHP後,我寫的代碼

$json = array(); 
for ($x=1; $x < $count + 1; $x++) { 
    $q_and_a = array(
     "Question" => $_POST["q".$x], 
     "Answer" => $_POST["a".$x] 
     ); 
    array_push($json, $q_and_a);  
} 
$encoded_array = json_encode($json); 
// Delete JSON file, create new one and push encoded array into file 
$json_file = 'questions.json'; 
unlink($json_file); 
$handle = fopen($json_file, 'w') or die('Cannot open file: '.$json_file); 
fwrite($handle, $json_string) or die('Internal Sever Error'); 

這個塊我得到一個內部服務器錯誤後,我意識到,這是因爲$json變量是一個數組;我需要將其轉換爲一個字符串,然後將其插入到文件中。我第一次使用serialize(),但只是插入一些奇怪的東西到我的文件。在將json數組移入文件之前,如何將json數組轉換爲字符串?

在前提前

+0

使用'file_put_contents()'保存到文件 – Dharman

+2

'$ json_string'永遠不會被定義!一個錯字? – Dharman

+0

大概你想「添加」到文件中,而不是替換內容?如果因爲您添加了一個而失去了100個問題,那就太糟糕了......確保您以允許追加的方式執行此操作。另外 - 你怎麼期望讀回這些信息?這影響了如何做到這一點。 – Floris

回答

1

試試這段代碼。它doen't使用JSON,但它仍然將數據保存到被拆分使用tab

<?php 
$count=10;//whatever you defined it to 
$qa = ""; 
for ($x=1; $x < $count + 1; $x++) { 
    $qa .= $_POST["q".$x]."\t".$_POST["a".$x]."\n"; 
} 
$json_file = 'file.txt'; 
unlink($json_file); 
file_put_contents($qa); 
?> 

<?php 
//to retrieve q&a 
$qas = file('file.txt',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); 
$qas = explode("\t",$qas); 
foreach($qas as $question => $answer) 
{ 
    //your code 

} 
?> 
0

的fwrite($處理,$ encoded_array)的文件或死亡(「內部中斷錯誤」);

相關問題