将fwrite输出格式化为外部文件 - 内爆错误

时间:2016-04-07 00:51:59

标签: php sql fwrite implode

我正在处理的代码通过php查询数据库,然后将结果放入一个名为CS的数组中。然后对此数组进行编码,以便它可以使用javascript。然后假设编辑输出,以便在每一行之后有一个换行符。后者是我遇到问题的地方。无论我如何编辑内爆函数,我每次都会得到内爆:无效参数传递

以下是代码:

<?php
$servername = "*****";
$username = "****";            --> edited for privacy.
$password = "*******";
$database = "********";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

// sql statement for tables and naming array to hold it in
$sql = "SELECT COURSE_ID FROM cs";
$result = $conn->query($sql);
$CS = array();

if ($result->num_rows > 0) {
      // fill array with results 
      while($row = $result->fetch_assoc()) {
          array_push($CS, $row);
      }
} else {
  echo "0 Results";
}
// encodes php array so it can be used in javascript
$json_array = json_encode($CS);

$conn->close();

// fills Computer_Science.js with the contents of the json_array and adds new lines in between
$json_array_lines = implode($json_array, "/n");     --> this line
$fp = fopen('..\js\DegreePlans\Computer_Science.js', 'w');
fwrite($fp, print_r($json_array_lines, TRUE));
fclose($fp);
?>

我对如何解决错误感到茫然。任何给予的帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我修好了!

<?php
$servername = "*****";
$username = "****";            --> edited for privacy.
$password = "*******";
$database = "********";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

// sql statement for tables and naming array to hold it in
$sql = "SELECT COURSE_ID FROM cs";
$result = $conn->query($sql);
$CS = array();

if ($result->num_rows > 0) {
  // fill array with results 
  while($row = $result->fetch_assoc()) {
      array_push($CS, $row);
  }
} else {
  echo "0 Results";
}
$conn->close();

//encode the array so it can be used in javascript and use regular expressions to format it.
$json_string = json_encode($CS);

$re = "/.,/";
$subst = "},\r\n";                                        --> right here!
$json_string = preg_replace($re, $subst, $json_string);

$fp = fopen('..\js\DegreePlans\Computer_Science.js', 'w');
fwrite($fp, print_r($json_string, TRUE));
fclose($fp);
?>