I use some code here, transfer mysql query data into json data and write into a file. where is the problem? why the file is zero kb?
while($row = mysql_fetch_array($Query)){
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
$countfile="data.txt";
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
$fp = fopen($countfile, 'r');
fwrite($fp, $jsondata);
fclose($fp);
}
Several things.
You dont need (and should avoid) to open the file in every iteration
You open the file read-only (r)
At all something like this should do it
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
fwrite($fp, $jsondata);
}
fclose($fp);
Additional you append separate json structures into the file, what is probably not, what you want. You should first collect all you want to store into one json structure and save it then
$data = array();
while($row = mysql_fetch_array($Query))
{
$data[] = array ('name'=>$row['name']);
}
file_put_contents('data.txt', json_encode($data));
This feels more like what you are probably looking for.
Because you're reopening the file as read only
$fp = fopen($countfile, 'r');
try
$fp = fopen($countfile, 'w'); // to write
or
$fp = fopen($countfile, 'a'); // to append
you could also open the file for writing at the start, append your rows in a variable and then write it all together to the file.
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata .= json_encode($arr) . "\n";
}
fwrite($fp, $jsondata);
fclose($fp);
You are opening the file read-only. You probably want 'w' or 'r+'.
You are opening the file for reading only
$fp = fopen($countfile, 'r');
You also dont need
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
just use:
$fp = fopen($countfile, 'w');
Related
I need to generate a CSV file from a MySQL query and save the file to an SFTP server. I have tried the code below. The CSV file gets created, but it is empty. I also receive an error message in the browser that says Warning: is_file() expects parameter 1 to be a valid path, resource given in regard to this line $sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);. If I move fclose($fp); to the last line, I don't get the error but data still doesn't appear in the file. Could someone please let me know how to get the data to save in the file that was created?
$fileName = 'dataFiles/reports/Report Summary/Report Summary.csv';
$sql = mysqli_query($db, "
SELECT *
FROM reports
WHERE reportID = 1
");
$fp = fopen('php://output', 'w');
$first = true;
while($row = mysqli_fetch_assoc($sql)){
if ($first) {
fputcsv($fp, array_keys($row));
$first = false;
}
fputcsv($fp, $row);
}
fclose($fp);
$sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);
Try something like this:
<?php
$fp = fopen('php://temp', 'r+');
// do stuff
rewind($fp);
$sftp->put($filename, $fp);
phpseclib (assuming you're using a new enough version) will detect that the second parameter is a stream resource and will try to read from it accordingly.
The second argument is not a handle but the content directly.
I think you could do: stream_get_contents($fp); in the second argument.
$content = stream_get_contents($fp);
fclose($fp);
$sftp->put($fileName, $content, NET_SFTP_LOCAL_FILE);
This is the code I've figured out.
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$json = '{"username":"'.$username.'",'.'"email":"'.$email.'"}';
$file = fopen('token_data.json','w+');
fwrite($file, $json);
fclose($file);
?>
But this is absolutely not the right way.
If your $_POST array has all of the data you need you can encode it as JSON and write to a file:
<?php
$json = json_encode($_POST);
$file = fopen('token_data.json','w+');
fwrite($file, $json);
fclose($file);
?>
If you want to append to the file you will need to read the file into an array first, add the newer parts of the array then encode it again before writing back to the file just like my friend #Rizier123 describes.
Okay, I found a more efficient way to do this.
Original Answer
// read the file if present
$handle = #fopen($filename, 'r+');
// create the file if needed
if ($handle === null)
{
$handle = fopen($filename, 'w+');
}
if ($handle)
{
// seek to the end
fseek($handle, 0, SEEK_END);
// are we at the end of is the file empty
if (ftell($handle) > 0)
{
// move back a byte
fseek($handle, -1, SEEK_END);
// add the trailing comma
fwrite($handle, ',', 1);
// add the new json string
fwrite($handle, json_encode($event) . ']');
}
else
{
// write the first event inside an array
fwrite($handle, json_encode(array($event)));
}
// close the handle on the file
fclose($handle);
}
Without decoding the whole JSON file into the arrays.
When I use this code, the new CVS file get "" by text with blanks:
//array in csv schreiben
$daten = array_filter($daten);
$csv_array[] = $daten;
$fp = fopen("golfDBtest.csv", 'w');
foreach ($csv_array as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The original CSV:
Reit im Winkel,69.8,131,68.4,126,71.6,129,69.5,127,70,7,4,5,4,13,5,3,4,1,4,9,4,17,3,15,3,11,4,10,4,14,4,18,3,4,4,2,4,8,3,16,5,6,3,12,5,00438640798250
The new file:
"Reit im Winkl",69.8,131,68.4,126,71.6,129,69.5,127,70,7,4,5,4,13,5,3,4,1,4,9,4,17,3,15,3,11,4,10,4,14,4,18,3,4,4,2,4,8,3,16,5,6,3,12,5,00438640798250
How can I write a CVS without ""?
Thanks
According to the documentation of fputcsv function it has a default enclosure value: ". Setting this so blank should help your cause.
I'd say this should work:
//array in csv schreiben
$daten = array_filter($daten);
$csv_array[] = $daten;
$fp = fopen("golfDBtest.csv", 'w');
foreach ($csv_array as $fields) {
fputcsv($fp, $fields, ",", "");
}
fclose($fp);
I am writing an "unfriend" script for my mini social network, basically the unfriend action needs to remove their id called: $user from their friend list and my id called: $my_id. I have made the scripts that add user id's to each users files but I am not sure how to delete this?
My friend_list file:
1,2,3 // I am user 1
Their friend_list file:
1,2,3 // They are user 3
I currently use this to add each id into the text file:
if($action === 'accept'){
mysql_query("DELETE FROM `friend_req` WHERE `from`='$user' AND `to`='$my_id'");
$fp = fopen($user_data['friend_list'], 'a');
fwrite($fp, ",".$user."");
fclose($fp);
$their_id = friend_list_from_user_id($user);
$fp = fopen($their_id, 'a');
fwrite($fp, ",".$my_id."");
fclose($fp);
}
But to remove $my_id from their friend_list and their $userid from my friend_list I'm thinking I need to use something like this but it isn't working:
if($action === 'unfriend'){
$fp = fopen($user_data['friend_list'], 'a');
unset($user);
fclose($fp);
$their_id = friend_list_from_user_id($user);
unset($my_id);
fclose($fp);
}
But that doesn't seem to work, what should I do to delete only the specified usernames from the respective file?
Oh, and also, this may/may not be of use:
$myFile = $file;
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
$friend = explode(',', $theData);
for($i=0; $i < count($friend); $i++){
if($i >= 0)
{
if($friend[$i] == $user_id) {
$their_user_id = $user_id;
}
}
To solve your issue just do something like:
//get the contents of the file
$contents = file_get_contents($user_data['friend_list']);
$contents = str_replace(",".$friend_id, "", $contents); //remove the friend's id
//open the file again and rewrite the whole thing with the new contents without that id
$fp = fopen($user_data['friend_list'], 'w+');
fwrite($fp, $contents);
fclose($fp);
I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/