$word, "part" => $part, "choices" => array() ); foreach ($lines as $line) { list($this_word, $this_pos, $this_defn) = preg_split("/[\t]+/", trim($line)); $json["choices"][] = array( "definition" => $this_defn, "correct" => $this_defn == $defn ? true : false ); } header("Content-type: application/json"); print pretty_json(json_encode($json)); // Return a human-readable version the given JSON. // Adapted from http://www.php.net/manual/en/function.json-encode.php#80339 function pretty_json($input) { $tab = "\t"; $nl = "\n"; $indent = 0; $in_string = false; $output = ""; for ($i = 0; $i < strlen($input); $i++) { $char = $input[$i]; $before = $after = ''; if (!$in_string) { switch ($char) { case '{': case '[': $after = $nl . str_repeat($tab, ++$indent); break; case '}': case ']': $before = $nl . str_repeat($tab, --$indent); break; case ',': $after = $nl . str_repeat($tab, $indent); break; case ':': $after = " "; break; case '"': if ($i == 0 || $input[$i-1] != '\\') { $in_string = true; } } } else if ($char == '"' && $input[$i-1] != '\\') { $in_string = false; } $output .= $before . $char . $after; } return $output; }