Advertisement
AMONRA75

PHP - MYSQL JSON TEXT FILE

Nov 14th, 2019
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.69 KB | None | 0 0
  1.  
  2. <?php
  3.  
  4. // Initialize variable for database credentials
  5. $dbhost = 'localhost';
  6. $dbuser = 'root';
  7. $dbpass = '';
  8. $dbname = 'history';
  9.  
  10. //Create database connection
  11.   $dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
  12.  
  13. //Check connection was successful
  14.   if ($dblink->connect_errno) {
  15.      printf("Failed to connect to database");
  16.      exit();
  17.   }
  18.  
  19. //Fetch 3 rows from actor table
  20.  
  21.   $result = $dblink->query("SELECT * FROM main");
  22.  
  23. //Initialize array variable
  24.   $dbdata = array();
  25.  
  26. //Fetch into associative array
  27.   while ( $row = $result->fetch_assoc())  {
  28.  
  29.   $row = array_map('utf8_encode', $row); //conversione per caratteri speciali èùòà
  30.   $dbdata[]=$row;
  31.  
  32.   //debug_zval_dump($dbdata);
  33.   }
  34.  
  35. //Print array in JSON format
  36.  //echo json_encode($dbdata);
  37.  
  38.  
  39.  
  40.  //echo "<pre>";
  41.  //echo json_encode($dbdata, JSON_PRETTY_PRINT);
  42.  //echo "</pre>";
  43.  
  44.  
  45.  
  46.  $myFile = "js_history_test.json";
  47.  $fh = fopen($myFile, 'w') or die("can't open file");
  48.  $stringData = json_encode($dbdata);
  49.  fwrite($fh, $stringData);
  50.  fclose($fh);
  51.  
  52.  
  53. //START FILE
  54.  $prepend = "
  55. [
  56.    {
  57.        \"id\":\"js_history\",
  58.        \"title\":\"ROMAN EMPIRE\",
  59.        \"description\":\"<p>descrizione</p>\",
  60.        \"focus_date\":\"-753-01-01 12:00:00\",
  61.        \"initial_zoom\":\"39\",
  62.        \"image_lane_height\":50,
  63.        \"events\":
  64.  ";
  65.  
  66. $file = 'js_history_test.json';
  67.  
  68. $fileContents = file_get_contents($file);
  69. echo $fileContents;
  70.  
  71.  
  72.  
  73.  
  74. //MIDDLE FILE
  75. file_put_contents($file, $prepend . $fileContents);
  76.  
  77.  
  78.  
  79. //END FILE
  80. $myfile = fopen("js_history_test.json", "a") or die("Unable to open file!");
  81. $txt = "}]";
  82. fwrite($myfile, "\n". $txt);
  83. fclose($myfile);
  84.  
  85.  
  86.  
  87.  ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement