Showing posts with label PHP FClOSE. Show all posts
Showing posts with label PHP FClOSE. Show all posts

Friday, 5 October 2018

PHP SNIPPET TO WRITE TO A FILE

Thursday, 30 August 2018

PHP - Create an associative array from the .txt file


This question already has an answer here:


  • CSV to Associative Array 5 answers
I have .txt file formatted as such:
    "id","dealer_id","vin","stockno",
    "1","2","3","4",
    "5","6","7","8",
    "9","10","11",12"

My goal is push this into an associative array like such:
    "id"=>"1", "dealer_id"=>"2", "vin"=>"3", "stockno"=>"4"

My question is, the data loops through for every 4 entries. In the example above, I should have 3 arrays created like such:
    "id"=>"1", "dealer_id"=>"2", "vin"=>"3", "stockno"=>"4"
    "id"=>"5", "dealer_id"=>"6", "vin"=>"7", "stockno"=>"8"
    "id"=>"9", "dealer_id"=>"10", "vin"=>"11", "stockno"=>"12"

How can I make this happen within PHP -- if possible at all?

Here's one approach:
<?php
$file = fopen('data.txt', 'r');
$headers = fgetcsv($file);
$result = array();
while ($row = fgetcsv($file)) {
        if (!$row[0]) continue;
        $nextItem = array();
        for ($i = 0; $i < 4; ++$i) {
                $nextItem[$headers[$i]] = $row[$i];
        }
        $result[] = $nextItem;
}
fclose($file);
var_dump($result);

This uses fgetcsv to read each delimited row of the file. The first row is used as the header names. Then, for each other row, we create a new entry and match the indexes to the header names. I set it to 4 because you have a trailing delimiter that creates an empty entry at the end, if you removed those from the input you could use the length of $headers for the inner loop.
Here is the result of the var_dump for your data:
array(3) {
  [0]=>
  array(4) {
    ["id"]=>
    string(1) "1"
    ["dealer_id"]=>
    string(1) "2"
    ["vin"]=>
    string(1) "3"
    ["stockno"]=>
    string(1) "4"
  }
  [1]=>
  array(4) {
    ["id"]=>
    string(1) "5"
    ["dealer_id"]=>
    string(1) "6"
    ["vin"]=>
    string(1) "7"
    ["stockno"]=>
    string(1) "8"
  }
  [2]=>
  array(4) {
    ["id"]=>
    string(1) "9"
    ["dealer_id"]=>
    string(2) "10"
    ["vin"]=>
    string(2) "11"
    ["stockno"]=>
    string(3) "12""
  }
}

Friday, 5 June 2015

PHP: Requires a file called counter1.dat in the same folder as the script

Requires a file called counter1.dat in the same folder as the script
CHMOD the counter file to 755
<?php
//simple counter example v1.0
//open the counter file in read only mode
$counterfile = "counter1.dat";
if(!($fp = fopen($counterfile,"r"))) die ("cannot open counter file");
//read the value stored in the file
$thecount = (int) fread($fp, 20);
//close the file
fclose($fp);
//increment the count
$thecount++;
//display the count
echo "visitor no : $thecount";
//open the file again in write mode and store
// the new count
$fp = fopen($counterfile, "w");
fwrite($fp , $thecount);
//close the file
fclose($fp);
?>

PHP: Display stock quotes from a CSV file, in this case Microsoft

<?php
//stock quote script
//this is the url for Microsoft's stock quote , we are opening it for reading
$fp = fopen ("http://finance.yahoo.com/d/quotes.csv?s=msft&f=sl1d1t1c1ohgv&e=.csv","r");
//this uses the fgetcsv function to store the quote info in the array $data
$data = fgetcsv ($fp, 1000, ",")
?>
<!-- this is our table which displays the stock info -->
<!-- we access the individual items by using $data[0]-->
<table>
<tr><td>description</td><td>latest figure</td><tr>
<tr><td>symbol</td><td><?php echo $data[0] ?></td></tr>
<tr><td>last price</td><td><?php echo $data[1] ?></td></tr>
<tr><td>date</td><td><?php echo $data[2] ?></td></tr>
<tr><td>time</td><td><?php echo $data[3] ?></td></tr>
<tr><td>change</td><td><?php echo $data[4] ?></td></tr>
<tr><td>open</td><td><?php echo $data[5] ?></td></tr>
<tr><td>high</td><td><?php echo $data[6] ?></td></tr>
<tr><td>low</td><td><?php echo $data[7] ?></td></tr>
<tr><td>volume</td><td><?php echo $data[8] ?></td></tr>
</table>
<?php
//close the filehandle $fp
fclose ($fp);
?>

Thursday, 4 June 2015

PHP: Atomic time

<?php
$fp = fsockopen("time-a.nist.gov", 37);
if ($fp) {
fputs($fp, "\n");
$timevalue = fread($fp, 49);
fclose($fp);
}

$atomic_time = (abs(hexdec('7fffffff') - hexdec(bin2hex($timevalue)) - hexdec('7fffffff')) - 2208988800);
echo $atomic_time;
?>

This returns the time in the form of a timestamp

Tuesday, 2 June 2015

PHP: Image to base64 string

<title>Image to Base64 String</title>
<fieldset>
    
<legend>Image to Base64 String</legend>
        
<center>
        
<form name="select_all">
                
 <?php 
                
/** 
 *   This code will help you to learn how we can convert an image into a base64 string!! 
 */ 
                    
echo"<h3><p>Image</p></h3>"; 
                    
//$file = File Image yang ingin di encode  
                    //Filetype: JPEG,PNG,GIF 
                    
$file "encode.jpg"; 
                    if(
$fp fopen($file,"rb"0)) 
                    { 
                    
$gambar fread($fp,filesize($file)); 
                    
fclose($fp); 

                     
                    
$base64 chunk_split(base64_encode($gambar)); 
                    
//Result 
                    
$encode '<img src="data:image/jpg/png/gif;base64,' $base64 .'" >'; 
                    echo 
$encode; 
                    }     
                
?> 

                
<br><textarea name="text_area" rows="20" cols="70">
 <? echo $encode?> </textarea>
                
<p><input type="button" value="Select All Code" onClick="javascript:this.form.text_area.focus();this.form.text_area.select();"></p>
        
</form>
        
</center>
    
</fieldset>

Monday, 23 February 2015

PHP: Generate CSV file from a PHP array

Here is a simple but efficient function to generate a .csv file from a PHP array. The function accept 3 parameters: the data, the csv delimeter (default is a comma) and the csv enclosure (default is a double quote).
<?php
function generateCsv($data, $delimiter = ',', $enclosure = '"') { 
$handle = fopen('php://temp', 'r+'); 
foreach ($data as $line) { 
fputcsv($handle, $line, $delimiter, $enclosure);
 } 
rewind($handle); 
while (!feof($handle)) { 
$contents .= fread($handle, 8192); 
}
 fclose($handle); 
return $contents; 
}
?>

Saturday, 4 October 2014

fwrite in PHP

fwrite — Binary-safe file write

Syntax:

int fwrite ( resource $handle , string $string [, int $length ] )
fwrite() writes the contents of string to the file stream pointed to by handle.

Parameters:

handle
A file system pointer resource that is typically created using fopen().

string
The string that is to be written.

length
If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Return values: fwrite() returns the number of bytes written, or FALSE on error.



Note:
Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:
<?php
function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}
?>
Note:
On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.
Note:
If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.
Note:
If writing twice to the file pointer, then the data will be appended to the end of the file content:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>


Example #1 A simple fwrite() example

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>
fputs — Alias of fwrite
This function is an alias of: fwrite().

unlink in PHP

unlink — Deletes a file
Syntax:

bool unlink ( string $filename [, resource $context ] )
Deletes filename. Similar to the Unix C unlink() function. A E_WARNING level error will be generated on failure.

Parameters:

filename
Path to the file.

context
Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.
Return values: Returns TRUE on success or FALSE on failure.

Changelog ¶

Version Description
5.0.0 As of PHP 5.0.0 unlink() can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers for a listing of which wrappers support unlink().


Example #1 Basic unlink() usage

<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);

unlink('test.html');
?>

ftell in PHP

ftell — Returns the current position of the file read/write pointer
Syntax:

int ftell ( resource $handle )
Returns the position of the file pointer referenced by handle.

Parameters:

handle
The file pointer must be valid, and must point to a file successfully opened by fopen() or popen(). ftell() gives undefined results for append-only streams (opened with "a" flag).

Return values: Returns the position of the file pointer referenced by handle as an integer; i.e., its offset into the file stream.

If an error occurs, returns FALSE.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.


Example #1 ftell() example

<?php

// opens a file and read some data
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);

// where are we ?
echo ftell($fp); // 11

fclose($fp);

?>

fflush in PHP

fflush — Flushes the output to a file
Syntax:

bool fflush ( resource $handle )
This function forces a write of all buffered output to the resource pointed to by the file handle.

Parameters:

handle
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return values: Returns TRUE on success or FALSE on failure.



Example #1 File write example using fflush()

<?php
$filename = 'bar.txt';

$file = fopen($filename, 'r+');
rewind($file);
fwrite($file, 'Foo');
fflush($file);
ftruncate($file, ftell($file));
fclose($file);
?>

fclose in PHP

fclose — Closes an open file pointer
Syntax:

bool fclose ( resource $handle )
The file pointed to by handle is closed.

Parameters:

handle
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().

Return values: Returns TRUE on success or FALSE on failure.



Example #1 A simple fclose() example

<?php

$handle = fopen('somefile.txt', 'r');

fclose($handle);

?>

Thursday, 4 September 2014

PHP: File functions In PHP

This chapter will explain following functions related to files:
  • Opening a file
  • Reading a file
  • Writing a file
  • Closing a file

Opening and Closing Files

The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.
Files modes can be specified as one of the six options in this table.
Mode Purpose
r Opens the file for reading only.
Places the file pointer at the beginning of the file.
r+ Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
w Opens the file for writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
w+ Opens the file for reading and writing only.
Places the file pointer at the beginning of the file.
and truncates the file to zero length. If files does not
exist then it attemts to create a file.
a Opens the file for writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
a+ Opens the file for reading and writing only.
Places the file pointer at the end of the file.
If files does not exist then it attemts to create a file.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.

Reading a file

Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
  • Open a file using fopen() function.
  • Get the file's length using filesize() function.
  • Read the file's content using fread() function.
  • Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those contents on the web page.
<html>
<head>
<title>Reading a file using PHP</title>
</head>
<body>

<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
   echo ( "Error in opening file" );
   exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );

fclose( $file );

echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>

</body>
</html>

Writing a file

A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.
The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
   echo ( "Error in opening new file" );
   exit();
}
fwrite( $file, "This is  a simple test\n" );
fclose( $file );
?>

<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>

<?php
if( file_exist( $filename ) )
{
   $filesize = filesize( $filename );
   $msg = "File  created with name $filename ";
   $msg .= "containing $filesize bytes";
   echo ($msg );
}
else
{
   echo ("File $filename does not exit" );
}
?>
</body>
</html>
We have covered all the function related to file input and out in PHP File System Function chapter.