Push file to array in loop - php

EDIT after all the answers, i updated the function, and it works
I read out a importfolder. In this folder are many different files available.
Step: I read the folder and add the files to a array
Step: I open every file and try to import
When i cant import a file, then this happens, when another file in this row have to be imported first.
Example: If I open a file "message to a address", this could not be imported, when the address are not added into the database. But in some other file of this filelist is the "create address"-file. When this is created, then it is good, when the "message to a address" will be added to the filelistarray on the end.
My Code give me an offset problem:
function importData( $path, $db, $mail )
{
//Get available Importfiles
$filelist = getFilelist( $path );
for ($i = 0; $i < count($filelist); $i++)
{
$filename = $path . "/" . $filelist[$i];
$file = fopen( $filename,"r" );
while(!feof( $file )) {
$items = explode( ";", fgets( $file ) );
//Get messagetyp
if( strtolower(trim($items[0])) == "nachrichtentyp" )
{
$messagetyp = $items[1];
break;
}
}
fclose($file);
if ( $messagetyp )
{
$f = "import" . $messagetyp;
if( !$f($filename, $db, $mail) )
{
array_push($filelist, $filelist[$i]);
}
}
}
}
This my error, when I push the element to the the filelist-array
PHP Warning: feof() expects parameter 1 to be resource, boolean given in /var/www/symfony/importscript/import.php on line 37
PHP Warning: fgets() expects parameter 1 to be resource, boolean given in /var/www/symfony/importscript/import.php on line 38

According to your errors, problem lies not in array_push but in fopen():
$file = fopen( $filename,"r" );
If php fails to open that file, variable $file will be set to false and because of that feof() and fgets() will give you errors.

You definitely should check if fopen returns another value than FALSE, maybe one of the files does not exist or you are restricted.

Related

fgetcsv throwing error when calling from CLI

Can run my php file fine when checking it via browser, but throws an infinite loop error when run via CLI:
fgetcsv() expects parameter 1 to be resource, boolean given on line 30 (while line)
Code:
readCSV("feeds/data.csv");
function readCSV($csvFile) {
$count = 0; //for counting array objects
$storedQuotes = array();
$handle = fopen($csvFile, 'r');
//fgetcsv($file, 1000, ","); //remove first line
while (($line = fgetcsv($handle, 1000, ",")) !== FALSE) {
$quote = $line[2];
$author = $line[1];
//add element to $csv_arr with $quote and $author
$csv_arr[]=array(
"quote" => $quote,
"author" => $author
);
}
fclose($file);
}
How can I get my program to run via php cli?
Check if $handle is a resource (or is false) first. For example:
$handle = fopen($csvFile, 'r');
if(false !=== $handle) {
// do while{} here
}
else {
echo "Could not open $csvFile for reading";
}
Also, in CLI, your file paths are different. So you need to be more explicit. The easiest way to do this, if $csvFile is located in a relative path to the script, is to define the path such as:
__DIR__ . "feeds/data.csv"
It seems like your PHP code doesn't find the file (because fopen returns false).
I think you should use full path instead of relative since you are running it in cmd.
You should set your path like the following:
readcsv(dirname(__FILE__).'/feeds/data.csv');
It should work if "feeds" directory is in the same directory as your PHP file.

Creating new files from an old one

while (($line = fgets($handle)) !== false) {
//look for the first payor block
if(strpos($line, 'N1*PR*') !== false || $block_start) {
$header_end = true; $block_start = true;
//see if the block finished
if(strpos($line, 'CAS*CO*45*20.43**253*1.27~') !== false) {
$block_start = false;
$payor_blocks[$count] .= $line;
$count++;
}
$payor_blocks[$count] .= $line;
} else {
//append to the header
if($header_end) {
$footer .= $line."\n";
} else {
$header .= $line."\n";
}
}
}
//get payor blocks and create a file foreach payor
$new_files = array();
foreach($payor_blocks as $block) {
$filename = $file . "_" . $count;
$count++;
$new_files[] = array(
'name' => $filename,
'content' => $header."\n".$block."\n".$footer
);
//loop through new files and create them
foreach($new_files as $new_file) {
$myfile = fopen($file, "x");
fwrite($myfile, $new_file['content']);
//close the file
fclose($myfile);
I have the code above, it's suppose to be able to open an original file called "$file" and create a new file then close it, However its not creating and when I run it, i get this warning error:
Warning: fopen(362931550.1a): failed to open stream:
File exists in /script2.php on line 90 Warning:
fwrite() expects parameter 1 to be resource,
boolean given in /script2.php on line 94 Warning:
fclose() expects parameter 1 to be resource, boolean
given in /script2.php on line 96
Any help is kindly appreciated.
I have one file named: 362931550.1a
I did a code that splits them at certain areas, (its pretty long to post), when i run the script I see it on my browser but it doesn't create 2 new files in the folder.
Your file open mode is incorrect.
From php.net documentation:
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING [...]
You should probably use 'w' mode:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
The script failed to open a stream with the fopen() function and return a boolean. The function fwrite() become the boolean value but need a resource.
The reason is that you only create files with the x-modifier in the stream.
Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it.
You see in the PHP manual more informations about the stream-modes (PHP manual).
To prevent this message check if the value isn't false.
$stream = fopen("file.txt", "x");
if($stream === false) {
echo "Error while open stream";
}
//here your code

Copying Images from URl list to my server all at once by php

I have big list of Urls in html file for images something like this :
image1
image2
image3
image4
image5
image6
image7
Around 50,000 Image
I want to make small script that can copy all images to my server so i can have them in :
http://Mywebsite.com/images/image1.jpg
http://Mywebsite.com/images/image1.jpg
http://Mywebsite.com/images/image1.jpg
...
I want to make loop and each Url in the list must be deleted after the image is copied successfully because sometimes if page crush on loading or something i can continue my loop without overwriting or reading again , if there is a better solution to not overwrite and read the url again please tell me.
I would create a script that reads your html file line per line. You can do that using fopen and fgets.
fopen("path/to/some/file", "r");
while ( ( $line = fgets( $handle ) ) !== false )
{
// do somehting with $line
}
This way the file gets not simply parsed into memory, so you don't have to worry about size
Then after parsing every line I would write down a lock file containing the current line number / index. So if your script crashes and you restart it the iteration simply skips every line until it's current index is higher than the index from the lock file.
the script
It might work but, in the end should not simply copy paste everything. But i hope it helps you finding your solution.
#!/usr/bin/env php
<?php
// I DID NOT TEST THIS!
// but it should work.
$handle = fopen("path/to/the/html/file/containing/the/urls.html", "r");
$storage = "path/where/you/want/your/images/";
$lockFile = __DIR__.'/index.lock';
$index = 0;
// get the lock index
if ( !file_exists( $lockFile ) )
{
file_put_contents( $lockFile, 0 );
}
// load the current index
$start = file_get_contents( $lockFile );
if ( $handle )
{
// line by line step by step
while ( ( $line = fgets( $handle ) ) !== false )
{
// update the
$index++;
if ( $start > $index )
{
continue;
}
// match the url from the element
preg_match( '/<a href="(.+)">/', $line, $url ); $url = $url[1];
$file = basename( $url );
// check if the file already exists
if ( !file_exists( $storage.$file )) //edited
{
file_put_contents( $storage.$file, file_get_contents( $url ) );
}
// update the lock file
file_put_contents( $lockFile, $index );
}
fclose($handle);
}
else
{
throw new Exception( 'Could not open file.' );
}
you can do something like this, of course you should also add here some error checking things :)
define("SITE_DIR", '/home/www/temp');
$file = file('in.txt');
foreach ($file AS $row){
preg_match('/(?<=\")(.*?)(?=\")/', $row, $url);
$path = parse_url($url[0], PHP_URL_PATH);
$dirname = pathinfo($path, PATHINFO_DIRNAME);
if (!is_dir(SITE_DIR . $dirname)){
mkdir(SITE_DIR . $dirname, 0777, true);
}
file_put_contents(SITE_DIR. $path, file_get_contents($url[0]));
}

Search file for word and delete line

This is a second request on the same subject. I wasn't clear
I needed the line to be deleted.
I searched here and found part of a script that is suppose search for
a word and delete the line. There seems to be a slight error with what
I'm trying to do.
I have an option list in a pull down. I would like for it to
remove the line selected. The file choice.php that is called
from the pull down page seems to be released when the php below
is called called because there is no access denied, or violation
errors.
These are the errors I'm getting after adding the 3 last lines I
was told I need.
fopen() expects at least 2 parameters, 1 given
implode(): Invalid arguments passed
fwrite() expects parameter 1 to be resource, boolean given
fclose() expects parameter 1 to be resource, boolean given
Thanks in advance
<?php
// Separate choice.php has the following pull down
// Select item to delete from list
// <option value="item1.php">Item 1</option>
// <option value="item2.php">Item 2</option>
// ...... many items.
$workitem = $_POST["itemtodelete"];
$file = file("option.list.php");
foreach( $file as $key=>$line ) {
if( false !== strpos($line, $workitem) ) {
unset ($file[$key]);
}
}
// Removed "\n"
$file = implode("", $file);
// Told to add this.
$fp = fopen ("option.list.php");
fwrite($fp,implode("",$file);
fclose ($fp);
?>
fopen requires a $mode as the second parameter, so that fails and everything that needs $fp.
Just use file_put_contents. It will even implode the array for you:
$workitem = $_POST["itemtodelete"];
$file = file("option.list.php");
foreach( $file as $key=>$line ) {
if( false !== strpos($line, $workitem) ) {
unset ($file[$key]);
}
}
file_put_contents('option.list.php', $file);
Ok. You are missing some closing parenthesis, as well as other things.
$replaceItem = $_POST['itemtodelete']; // You should filter this data
$newContents = "";
$path = PATH_TO_FILE; // This could be hard coded, but not recommended
$filename = "option.list.php";
// Check to see if the file exists
if ( file_exists($path."/".$filename) ) {
// Wrap our IO stuff so we catch any exceptions
try {
// Open the file for reading
$fp = fopen($path."/".$filename, "r");
if ($fp) {
// Loop line-by-line through the file
while($line = fgets($fp, 4096) !== false) {
// Only add the line if it doesn't contain $replaceItem
// This is case insensitive. I.E. 'item' == 'ITEM'
// For case sensitive, use strstr()
if ( stristr($line, $replaceItem) == false ) {
$newContents .= $line;
}
}
}
// Close our file
fclose($fp);
// Replace the contents of the file with the new contents
file_put_contents($path."/".$filename, $newContents);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
}
Edit: Try this. I modified it somewhat.

feof(): 3 is not a valid stream resource in

after i have installed windows 8 on my desktop and reinstalled aptana and xampp, i somehow can't use !feof($handle). i want to get the symbols of nasdaq stored in my $symb arra.here is an example and my error:
$symb = array();
$url = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
$handle = fopen("$url","r");
while( !feof($handle) ){
$line = fgetcsv($handle, 1024);
if($line!="Symbol" && isset($line[0]) && $line[0] != null ){
$symb[] = trim($line[0]);
}
fclose($handle);
}
And my Errors :
Warning: feof(): 3 is not a valid stream resource in C:\xampp\htdocs\demos\screener\candleScreener.php on line 61
Warning: fgetcsv(): 3 is not a valid stream resource in C:\xampp\htdocs\demos\screener\candleScreener.php on line 62
Warning: fclose(): 3 is not a valid stream resource in C:\xampp\htdocs\demos\screener\candleScreener.php on line 66
.......
Is there a setting i have to change on the php.ini file or what could it be ?
thanks.
.....
$url = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
$handle = fopen("$url","r");
$txt = fread( $handle, 8 );
print_r($txt);
.....
prints out :
"Symbol"
so my fopen() is fine ....
The reinstallation and the fopen() are red herrings. You're closing the file handle inside the while loop, before the file has been read.
while( !feof($handle) ){
$line = fgetcsv($handle, 1024);
if($line!="Symbol" && isset($line[0]) && $line[0] != null ){
$symb[] = trim($line[0]);
}
// fclose($handle); // Move this outside the while loop
}
fclose($handle); // Moved this outside the while loop
I had the same problem in my code. I had an extra file close function in the code. In other words I was trying to write to the file for a second time and it was not open for use. I had this coded in the top of my program:
$newFile = $local_directory . $tenant.'-'.$namespace.'_Stats.xml';
$newDoc = fopen($newFile, "w");
fwrite($newDoc, $urlStats);
fwrite($newDoc, $response);
fclose($newDoc);
Then later I had:
fwrite($newDoc, $response);
fclose($newDoc);
Check to make sure the file is open before you write more content.

Categories