PHP script for generating HTML files stopping early - php

I am extremely new to PHP and am having some issues with my first script. I am attempting to use this PHP script to generate HTML files for a series of products that only have minor changes between them. I have a .csv spreadsheet with all of the information, an html template and the PHP script I will post below.
Here is the problem I am encountering. When I check the folder where the script is supposed to put my finished HTML files after running the script, there are only 4 files instead of the 36 I want it to make. There are 36 rows of information in the .csv and I can't figure out how to get the script to generate all of the HTML files it should.
Here is my script:
<?php
$base_template = file_get_contents('template.html');
$file_to_read = 'spreadsheet.csv';
ini_set("auto_detect_line_endings", 1);
$filename = '';
if (($handle = fopen($file_to_read, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$Column1 = $data[0];
$Column2 = $data[1];
$Column3 = $data[2];
$Column4 = $data[3];
$Column5 = $data[4];
$Column6 = $data[5];
$Column7 = $data[6];
$filename = preg_replace('/[\s\W]+/','',$Column1);
$filename = substr($filename, 0, 10);
$template = str_replace('{Column1}', $Column1, $base_template);
$template = str_replace('{Column2}', $Column2, $template);
$template = str_replace('{Column3}', $Column3, $template);
$template = str_replace('{Column4}', $Column4, $template);
$template = str_replace('{Column5}', $Column5, $template);
$template = str_replace('{Column6}', $Column6, $template);
$template = str_replace('{Column7}', $Column7, $template);
$file = fopen('generated_html/'.$filename.'.html',"w+");
fwrite($file, $template);
fclose($file);
}
fclose($handle);
}
?>
How can I get the script to generate all of the files I need instead of stopping early?

Related

Error "Warning: file(...): failed to open stream: No such file or directory in ..." when trying to read an uploaded file

I've read other posts about this error but I couldn't find the one that suit my case.
This is the problem: after uploading a content (text file) on a specific server path (I'm using an Apache local server), I can't read it with the file() function, except when the file is contained also in the main directory (__DIR__).
This is the problematic portion of the script:
$uploaddir = __DIR__.'/cbi_files/';
if (!is_dir($uploaddir))
mkdir($uploaddir);
chmod($uploaddir, 0600);
// Recovering temporary directory
$userfile_tmp = $_FILES['cbi_file']['tmp_name'];
// Recovering originary file's name
$userfile_name = $_FILES['cbi_file']['name'];
$count=0;
$operazione = 0;
$file_caricati = array();
foreach ($_FILES['cbi_file']['name'] as $filename) {
$destination = $uploaddir;
$origin = $_FILES['cbi_file']['tmp_name'][$count];
$count++;
$destination = $destination.basename($filename);
// moving files from temporary directory to destination
$operazione = move_uploaded_file($origin, $destination);
$file_caricati[] = $filename;
}
$file_cbi = array();
$righe = array();
if (is_dir($uploaddir)) {
if ($dh = opendir($uploaddir)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..') {
$righe = file($file, FILE_IGNORE_NEW_LINES); // I get the error on this line
$last_row = count($righe)-1;
include(__DIR__.'/scriptCBI.php');
$file_cbi[] = array(
'nome_file' => $file,
'codice_RH' => $righe[0],
'codice_EF' => $righe[$last_row],
'recs' => $rec_array
);
}
}
closedir($dh);
}
}
I get the error if I keep the file only in $uploaddir = __DIR__'/cbi_files/', but if I keep it both in this directory and in the main directory (__DIR__) it works properly.
How's that possible?

search, insert & write on a new line of text file using PHP

i have problems in searching a string in a file, insert a new line after the searched string and write on the new added line. currently i am using below code from examples and discussion i found:-
$target = '<18>';
$put = 'Enter';
$file = 'line.txt';
$filename = $file;
$string_i_am_looking_for = $target;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$string_i_am_looking_for] = $put;
file_put_contents( $filename , implode( "\n", $lines ) );
text file:-
<17>
<18>
<19>
<20>
at first action, i was able to put the $put in the text file.
<17>
<18>Enter
<19>
<20>
but, when i change the $target = "<20>", i was not able to write after the new $target. It will appear next to the first line. And when i reload the page more and more, it will keep on writing on the first line. Below is the result:-
<17>EnterEnterEnterEnterEnter
<18>Enter
<19>
<20>
Word Enter is not new line in any manner. You have to replace it with \r\n or \n (depends on file new line character).
$target = '<18>';
$put = "\r\n";
$file = 'line.txt';
Try This
$target = '<20>';
$put = 'Enter';
$file = 'line.txt';
$filename = $file;
$string_i_am_looking_for = $target;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$key = array_search($string_i_am_looking_for,$lines);
$toSearch = $target.$put;
if(!in_array($toSearch,$lines)) {
$lines[$key] = $target.$put;
}
file_put_contents( $filename , implode( "\n", $lines) );

Issue with multiple image write

Now I am fed up with this issue, have been trying to fix it since 2-3 days.
The problem:
I am downloading certain images, and then writing them on to disk with php script.
The images are high resolution may be around 7000 pixels. The data is being downloaded properly.
When I write this data on to file, some time 1 image gets write, some times 2,3 etc.
The script is not showing any error and just breaks.
I don't have access to server logs and can't check those either.
It breaks after curl_get_contents , means where I write file, if I comment that section it works properly.
Below is the code:
<?php
ini_set ("display_errors", "1");
error_reporting(E_ALL);
ini_set('max_execution_time', 3000);
include_once("../config.php");
include_once("../utils.php");
$DIR = "../wallpapers";
$URL = "Website url";
$info = array();
$dom = new domDocument;
#$dom->loadHTML(file_get_contents($URL));
$dom->preserveWhiteSpace = false;
$links = $dom->getElementsByTagName('img');
$i = 0;
foreach ($links as $tag){
$iurl = $tag->getAttribute('src');
$lastHyphenAt = strrpos($iurl, "-");
$iurl = substr ($iurl, 0, $lastHyphenAt).".jpg";
$info[$i]["url"] = $iurl;
$info[$i]["name"] = basename($iurl);
$i++;
}
foreach($info as $item){
$url = $item["url"];
$name = $item["name"];
if(!file_exists($DIR."/".$name)){
echo "Downloading: ".$url."<br><br>";
$data = curl_get_contents($url);
$file = fopen($DIR."/".$name,"w") or die('Cannot open file: '.$my_file);
fwrite($file,$data);
fclose($file);
}else
echo "Exists ".($DIR."/".$name)."<br><br>";
}
?>
you can write high resolution images by applying chunk functionality, check below code for the same :-
$chunk = 102400;
$filePointer = fopen($url, "rb");
if ($filePointer!=false){
while (!feof($filePointer))
{
if($chunk<TOTALFILESIZE)
{
$fileData = fread($filePointer, 102400); //102400 is chunk size
$myFile = $DIR."/".$_REQUEST['filename'].'.'.$_REQUEST['ext']; //store the file into temp. location
chmod($myFile, 0777);
$fp = fopen($myFile, 'a+');
fwrite($fp, $fileData);
fclose($fp);
}
}
}

Convert XLSX to JSON

I am writing a script to basically convert an excel file to JSON. The file is a giant budget with hundreds of lines. I used the PHPExcel library to convert the xlsx file into a csv. I then converted the excel file into a json, but am receiving an error:
Warning: array_combine(): Both parameters should have an equal number of elements
Here is my code
<?php
ini_set('memory_limit', '1000M');
require_once 'classes/PHPExcel/IOFactory.php';
$excel = PHPExcel_IOFactory::load("sap.xlsx");
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(",");
$writer->setEnclosure("");
$writer->setLineEnding("\r\n");
$writer->setSheetIndex(0);
$writer->save("sap.csv");
function getJsonFromCsv($file,$delimiter) {
if (($handle = fopen($file, 'r')) === false) {
die('Error opening file');
}
$headers = fgetcsv($handle, 4000, $delimiter);
$csv2json = array();
while ($row = fgetcsv($handle, 4000, $delimiter)) {
$csv2json[] = array_combine($headers, $row);
}
fclose($handle);
return json_encode($csv2json);
}
$file = 'sap.csv';
echo getJsonFromCsv($file, ',');
What do I need to do to make this work? Or really just convert a large xlsx file to JSON..
Thanks

PHP reading file

I am trying to read a formatted file
name (read this into variable)
10 10 (read into separate variables)
the rest into array
line
line
line
line
to clarify this is for an upload script which i already finished when a user uploads a file formatted like that it reads it in the way described above
$fname = 'test.txt';
$lines = file("$fname", "r");
while($lines as $currenline){
I am trying to put the name, width, height into variables
then the rest into the array
}
will this help
Not 100% sure what you're asking for but maybe this can get you started:
$fname = 'test.txt';
$lines = file("$fname", "r");
foreach($lines as $line) {
$parts = explode(' ', $line);
$name = $parts[0];
$width = $parts[1];
$height = $parts[2];
// Do whatever you want with the line data here
}
It assumes all input lines are well formatted of course.
$fh = fopen( $fname, 'r' );
$name = fgets( $fh );
$dimensions = split( ' ', fgets($fh) );
$length = $dimensions[0];
$width = $dimensions[1];
$lines = array();
while ( $line = fgets( $fh ) $lines[] = $line;
I never tested this, but it should work if your files are constant. The while loop maybe off, and need some re-working if it doesn't work, keeping in mind that fgets returns false if an error occurs or is unable to read the file.
$lines already contains almost what you need, just pull out the relevant pieces.
$fname = 'test.txt';
$lines = file("$fname", "r");
$name = $lines[0];
list($height, $width) = explode(' ', $lines[1]);
$lines = array_slice($lines, 2);
Note this doesn't have any error checking, so you might want to add some.
As suggested in the comments you can also do this using array_shift:
$fname = 'test.txt';
$lines = file("$fname", "r");
$name = array_shift($lines);
list($height, $width) = explode(' ', array_shift($lines));
// $lines now contains only the rest of the lines in the file.

Categories