user6158055 user6158055 - 6 months ago 11
SQL Question

Write query result to txt file

The query results come from the oracle how to write to a text file in php.These codes write to html table.I want implement as write text fle.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res);

foreach ($res as $col) {
echo "<tr>\n";
foreach ($col as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Answer

You could take the entire result and write it in json

function save_result($result, $location) {
 $json = json_encode($result);
 $file = fopen($location, 'w');
 fwrite($file, $json);
 fclose($file);
}

function get_result($result, $location) {
 $file = fopen($location, 'r');
 $read = json_decode(fread($file, filesize($location)));
 fclose($location);
 return $read;
}

Usage:

save_result($result, 'hello.txt'); //Save

get_result('hello.txt'); //Read