I am getting undefined offset. Please help, I can't find where's the problem at all :(
<?php
$fileTitle = $_GET['title'];
$rawData = $_GET['data'];
//fileTitle is testing
//rawData is 5000013,0.00,0.00,50.00,0+5006529,0.00,0.00,50.00,0
$lineData = explode("+",$rawData)
for( $i=0 ; $i<count($lineData) ; $i++)
{
$txtFileTitle = $fileTitle.".txt";
$txtFileLineData = $lineData[$i]."\r\n";
$txtFileStatus = file_put_contents($txtFileTitle, $txtFileLineData, FILE_APPEND);
if($txtFileStatus != false)
{
echo "SUCCESS: data written to txt file";
}
else
{
echo "FAIL: could not write to txt file";
}
}?>
The result is a .txt file with:
5000013,0.00,0.00,50.00,0+5006529,0.00,0.00,50.00,0
What i want is a .txt with:
5000013,0.00,0.00,50.00,0
5006529,0.00,0.00,50.00,0
I think the issue was due to the <= in the loop - as the counter begins at zero it would exceed the actual count by one and thus create the undefined index error.
<?php
$title = $_GET['title'];
$data = $_GET['data'];
//title is testing
//data is 5000013,0.00,0.00,50.00,0+5006529,0.00,0.00,50.00,0
$lines = explode( "+", $data );
$file = $title . ".txt";
for( $i=0 ; $i < count( $lines ); $i++ ){
$content = $lines[ $i ] . PHP_EOL;
$status = file_put_contents( $file, $content, FILE_APPEND );
echo $status ? 'SUCCESS: data written to txt file' : 'FAIL: could not write to txt file';
}
?>
edit
The use of + in the source data is ambiguous because the + is used in urls when they are encoded ( space )
<?php
$title = $_GET['title'];
$data = urlencode( $_GET['data'] );
$lines = explode( "+", $data );
$file = __DIR__ . '/' . $title . ".txt";
for( $i=0 ; $i < count( $lines ); $i++ ){
$content = urldecode( $lines[ $i ] ) . PHP_EOL;
$status = file_put_contents( $file, $content, FILE_APPEND );
echo $status ? 'SUCCESS: data written to txt file' : 'FAIL: could not write to txt file';
}
?>
You can simple to use preg_replace function to replace + whith space
$fileTitle = $_GET['title'];
$rawData = $_GET['data'];
$txtFileLineData = preg_replace('/\+/', ' ', $rawData);
$txtFileTitle = $fileTitle.".txt";
$txtFileStatus = file_put_contents($txtFileTitle, $txtFileLineData, FILE_APPEND);
if ($txtFileStatus != false) {
echo "SUCCESS: data written to txt file";
} else {
echo "FAIL: could not write to txt file";
}
Related
i wrote a convert bulk data from an excel to a .txt or .csv by using fwrite php. however when I fread on the .txt file that my data placed on, the data turned out broken line. how can i fix it? Attached here is the highlighted from .txt or .csv and also the codes as below:-
**********my write code *************
for loop here {
$split_filename_path = fopen($tempfile_path.$split_filename.$total_round.$extension, "w");`
$split_file_txt = $ISBN.$comma.$Title.$comma.$Qty.$comma.$Location.$comma.$outlet;
fwrite($split_filename_path, $split_file_txt);
}
fclose($split_filename_path);
then it comes here
my read code*****
$myfile = fopen($file, "r");
$fread = fread($myfile,filesize($file));
fclose($myfile);
$split = explode("\n",$fread);
$datafields = array('ISBN', 'title', 'qty', 'location', 'outlet');
$insertvalues = array();
foreach($split as $string){
$row = explode(",",$string);
$questionmarks[] = '(' . $this->placeholder('?',$irow, sizeof($row)) . ')';
$insertvalues = array_merge( $insertvalues, array_values($row));
}
$sql = "INSERT INTO temp_data (".implode( ',', $datafields) . ")
VALUES ". implode( ',', $questionmarks);
function placeholder( $text, $irow, $count = 0, $separator = ',' ) {
$result = array();
if ($count > 0) {
for ($x = 0; $x < $count; $x++) {
$result[] = $text;
}
}
return implode($separator, $result);
}
with this codes, the result that I have is here :
9780794435295,BARBIE & HER SISTERS IN THE GREAT PUPPY ADVENTURE: (supposed to be full :- BARBIE & HER SISTERS IN THE GREAT PUPPY ADVENTURE: A SLIDING TAB BOOK BARBIE MOVIE TIEIN )
found the answer.
$Title = preg_replace( "/\r|\n/", "", $Title);
I want to get the picture in the resume PDF or make a copy of it. I already tried some code from the internet but it is not working or the image must have effect like shadow or glow to work, I need a PHP code that can get image/Picture. For example, when i upload resume PDF, I want to get the 2x2 picture from it or make a copy of it.
These is the code that I already tried but it only works when the images have effects.
require_once('lib/nusoap.php');
class extractImagesFromPdf {
public function toByteArray($file01)
{
if (!($fp = fopen($file01, "r")))
die ("can not open file: " . $file01) ;
$file = file_get_contents($file01);
$byteArr = str_split($file);
$length = sizeof($byteArr) ;
$data = "" ;
for($i = 0; $i < $length; $i++) {
$data .= base64_encode($byteArr[$i]);
}
return $data ;
}
function main ($subSerial, $fileContent)
{
$client = new nusoap_client("http://www.biclim.com/WS/BCService?wsdl", true);
$params[] = array('subSerial' => $subSerial,
'fileContent' => $fileContent
);
$result = $client->call("extractImagesFromPdf", $params);
$images = $result["extractImagesFromPdfResponse"];
print_r($images);
$i = 0;
$theDate = date("dmY_His") ;
foreach($images AS $image) {
$fp = fopen('d:/fileImages_Page' . $image['pageNumber'] . "_image" . $i . "_" . $theDate . "." . $image['imageType'], 'w');
print "\nExtracting Image " . $i . " in Page :" . $image['pageNumber'] ;
fwrite($fp, base64_decode($image['content']));
fclose ($fp);
$i = $i + 1;
}
}
}
$subSerial = "DEMO";
$extractImagesFromPdf = new extractImagesFromPdf() ;
$fileContent = $extractImagesFromPdf->toByteArray("D:/2.pdf") ;
$extractImagesFromPdf->main($subSerial, $fileContent);
I have a number of DBF database files that I would like to convert to CSVs. Is there a way to do this in Linux, or in PHP?
I've found a few methods to convert DBFs, but they are very slow.
Try soffice (LibreOffice):
$ soffice --headless --convert-to csv FILETOCONVERT.DBF
Change the files variable to a path to your DBF files. Make sure the file extension matches the case of your files.
set_time_limit( 24192000 );
ini_set( 'memory_limit', '-1' );
$files = glob( '/path/to/*.DBF' );
foreach( $files as $file )
{
echo "Processing: $file\n";
$fileParts = explode( '/', $file );
$endPart = $fileParts[key( array_slice( $fileParts, -1, 1, true ) )];
$csvFile = preg_replace( '~\.[a-z]+$~i', '.csv', $endPart );
if( !$dbf = dbase_open( $file, 0 ) ) die( "Could not connect to: $file" );
$num_rec = dbase_numrecords( $dbf );
$num_fields = dbase_numfields( $dbf );
$fields = array();
$out = '';
for( $i = 1; $i <= $num_rec; $i++ )
{
$row = #dbase_get_record_with_names( $dbf, $i );
$firstKey = key( array_slice( $row, 0, 1, true ) );
foreach( $row as $key => $val )
{
if( $key == 'deleted' ) continue;
if( $firstKey != $key ) $out .= ';';
$out .= trim( $val );
}
$out .= "\n";
}
file_put_contents( $csvFile, $out );
}
Using #Kohjah's code, here an update of the code using a better (IMHO) fputcsv approach:
// needs dbase php extension (http://php.net/manual/en/book.dbase.php)
function dbfToCsv($file)
{
$output_path = 'output' . DIRECTORY_SEPARATOR . 'path';
$path_parts = pathinfo($file);
$csvFile = path_parts['filename'] . '.csv';
$output_path_file = $output_path . DIRECTORY_SEPARATOR . $csvFile;
if (!$dbf = dbase_open( $file, 0 )) {
return false;
}
$num_rec = dbase_numrecords( $dbf );
$fp = fopen($output_path_file, 'w');
for( $i = 1; $i <= $num_rec; $i++ ) {
$row = dbase_get_record_with_names( $dbf, $i );
if ($i == 1) {
//print header
fputcsv($fp, array_keys($row));
}
fputcsv($fp, $row);
}
fclose($fp);
}
I have a txt file that I want to read backwards, currently I'm using this:
$fh = fopen('myfile.txt','r');
while ($line = fgets($fh)) {
echo $line."<br />";
}
This outputs all the lines in my file.
I want to read the lines from bottom to top.
Is there a way to do it?
First way:
$file = file("test.txt");
$file = array_reverse($file);
foreach($file as $f){
echo $f."<br />";
}
Second Way (a):
To completely reverse a file:
$fl = fopen("\some_file.txt", "r");
for($x_pos = 0, $output = ''; fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
$output .= fgetc($fl);
}
fclose($fl);
print_r($output);
Second Way (b):
Of course, you wanted line-by-line reversal...
$fl = fopen("\some_file.txt", "r");
for($x_pos = 0, $ln = 0, $output = array(); fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
$char = fgetc($fl);
if ($char === "\n") {
// analyse completed line $output[$ln] if need be
$ln++;
continue;
}
$output[$ln] = $char . ((array_key_exists($ln, $output)) ? $output[$ln] : '');
}
fclose($fl);
print_r($output);
Try something simpler like this..
print_r(array_reverse(file('myfile.txt')));
Here is my solution for just printing the file backwards. It is quite memory-friendly. And seems more readable (IMO [=in my opinion]).
It goes through the file backwards, count the characters till start of a line or start of the file and then reads and prints that amount of characters as a line, then moves cursor back and reads another line like that...
if( $v = #fopen("PATH_TO_YOUR_FILE", 'r') ){ //open the file
fseek($v, 0, SEEK_END); //move cursor to the end of the file
/* help functions: */
//moves cursor one step back if can - returns true, if can't - returns false
function moveOneStepBack( &$f ){
if( ftell($f) > 0 ){ fseek($f, -1, SEEK_CUR); return true; }
else return false;
}
//reads $length chars but moves cursor back where it was before reading
function readNotSeek( &$f, $length ){
$r = fread($f, $length);
fseek($f, -$length, SEEK_CUR);
return $r;
}
/* THE READING+PRINTING ITSELF: */
while( ftell($v) > 0 ){ //while there is at least 1 character to read
$newLine = false;
$charCounter = 0;
//line counting
while( !$newLine && moveOneStepBack( $v ) ){ //not start of a line / the file
if( readNotSeek($v, 1) == "\n" ) $newLine = true;
$charCounter++;
}
//line reading / printing
if( $charCounter>1 ){ //if there was anything on the line
if( !$newLine ) echo "\n"; //prints missing "\n" before last *printed* line
echo readNotSeek( $v, $charCounter ); //prints current line
}
}
fclose( $v ); //close the file, because we are well-behaved
}
Of course replace PATH_TO_YOUR_FILE with your own path to your file, # is used when opening the file, because when the file is not found or can't be opened - warning is raised - if you want to display this warning - just remove the error surpressor '#'.
If the file is not so big you can use file():
$lines = file($file);
for($i = count($lines) -1; $i >= 0; $i--){
echo $lines[$i] . '<br/>';
}
However, this requires the whole file to be in memory, that's why it is not suited for really large files.
Here's my simple solution without messing up anything or adding more complex code
$fh = fopen('myfile.txt','r');
while ($line = fgets($fh)) {
$result = $line . "<br>" . $result;
}
echo $result // or return $result if you are using it as a function
I have many PDFs in a folder. I want to extract the text from these PDFs using xpdf. For example :
example1.pdf extract to example1.txt
example2.pdf extract to example2.txt
etc..
here is my code :
<?php
$path = 'C:/AppServ/www/pdfs/';
$dir = opendir($path);
$f = readdir($dir);
while ($f = readdir($dir)) {
if (eregi("\.pdf",$f)){
$content = shell_exec('C:/AppServ/www/pdfs/pdftotext '.$f.' ');
$read = strtok ($f,".");
$testfile = "$read.txt";
$file = fopen($testfile,"r");
if (filesize($testfile)==0){}
else{
$text = fread($file,filesize($testfile));
fclose($file);
echo "</br>"; echo "</br>";
}
}
}
I get blank result. What's wrong with my code?
try using this :
$dir = opendir($path);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$content = shell_exec('C:/AppServ/www/pdfs/pdftotext '.$filename.' ');
$read = strtok ($filename,".");
$testfile = "$read.txt";
$file = fopen($testfile,"r");
if (filesize($testfile)==0){}
else{
$text = fread($file,filesize($testfile));
fclose($file);
echo "</br>"; echo "</br>";
}
}
You do not have to create a temporary txt file
$command = '/AppServ/www/pdfs/pdftotext ' . $filename . ' -';
$a = exec($command, $text, $retval);
echo $text;
if it does not work check the error logs of the server.
The lines
echo "</br>";
echo "</br>";
should be
echo "</br>";
echo $text."</br>";
Hope this helps