I'd like to run a function within a While loop.
Unfortunately, it works but not quite as desired.
My goal is to read out from a CSV file, each line and is stored in the MySQL database. This also works flawlessly.
In addition, however, I want to let miteinpflegen a value by a numeric random.
Here again my scripts to generate the numerical codes.
function generateCode($length){
$string = "";
$numbers = "0123456789";
for($i=0;$i < $length;$i++) {
$char = $numbers[mt_rand(0, strlen($numbers)-1)];
$string .= $char;
}
return $string;
}
$gencode = generateCode(8);
Works great.
And here my while loop ($handle is in my case the var to open CSV file)
while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
$import = "INSERT into jobs(id,link_id,random number) values('NULL','$linkid','$gencode')";
mysql_query($import) or die(mysql_error());
}
But how do I get it back now that each line of the CSV file gets its own random number or rather, which is calculated in each row $gencode new?
At the moment i get one random number for all rows.
For help, I am very grateful.
I just can no longer see the forest for the trees.
Thank you
You can simply call your own function generateCode() like any other function inside your loop:
while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
$gencode = generateCode(8);
// the rest of your code
}
Just make sure that generateCode() is already defined when you call it.
Related
I am importing a CSV file which contains list of URLS. These URLs are displaying in tabular format to perform some operations. But a space is added to the beginning of url. Because of this the operations I am performing on it fails. So how I can remove that space.When I done print_r() in my controller it shows result as
�https://www.surveygizmo.com
if (($handle = fopen($filename, "r")) !== FALSE)
{
while (($value = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($value);
for ($c=0; $c < $num; $c++)
{
echo "<pre>";
print_r($value[$c]);
Above a few lines of code. I am getting symbol,� before the content.
How can I remove that? I tried with trim. But still its not working. I need help. Thank you
Try this. I have similar issue and after following tweak it fixed
$col_val = $value[$c];
$final_value = trim($col_val ," \t\n\r\0\x0B\"");
print_r($final_value);
I'm having troubles with a function that create html from a csv file with php functions fgetcsv() and echo.
Here's the code:
<?php function getContent($data) {
if (($handle = fopen($data, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
echo <p>...</p>
}
}
} ?>
It outputs an html table and then, I would like to use this with the function fwrite() to write it into a new html file that I just created. Now, I just tried to use it as a variable like this:
$content = getContent($data);
fwrite($file, $content);
But it's not working... Any idea ?
P.S: I have a lot of echo in the getContent function, this is why I don't want to use a variable.
(disclaimer: I understand your current function does echo what you want, so I'm assuming your echo-line is modified for this example, and it contains something with that $data in real,right?)
Echo prints to screen, and you don't want that, so save it and return it as a string.
quick example:
function getContent($data) {
$result = ""; //you start with an empty string;
if (($handle = fopen($data, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$result .= "<p>...</p>"; //add what you used to echo to the string
}
}
return $result; //send your string back to the caller of the function
}
now you can call that function and do stuff with your string. First, test it with echo:
$content = getContent($data); //gets you the data in a string
echo $content; //echoes it, just like you did before.
if that works and you have something you can write your content to (that $file must be defined obviously, you can do what you did:
$content = getContent($data); //still gets you the data
fwrite($file, $content); //writes it to a file.
Now, if the write doesn't work, you should debug that first with a string you hardcode, but that hasn't got much todo with the issue in this question.
I eventually changed my echo with a variable $text that I concatenated like this $text .= "<p>...</p>"
Afterwards, I just needed to use this variable to create the html file.
I am new at php programming but I have been stuck with this code for some time.
I would like to read a .csv file line by line and then save its values in a list of arrays.
$file = fopen('Sub-Companies.csv', 'r');
while (($line =
fgetcsv($file)) !== FALSE) {
print_r($line);
list($customer_id[],$company_name[],$department[],$employee[],$country[],$zipcode[],$address[],$city[],
$smth1[], $smth2[], $phone_no1[],$phone_no2[],$email[],$website[],
$customer_no[],$problem1[],$problem2[]) = explode(";",$line); }
fclose($file); var_dump($customer_id);
The problem is that, although it is read correctly the file, then the explode is not working and the arrays appear to be null.
One thing that I am considering is that some arrays have more ";" than others, so that might be a problem, that is why I have the arrays $problem1 and $problem2, in order to store the values of this arrays.
Any help would be great!
You're using fgetcsv() in the wrong way.
We've come to this solution while chatting here on StackOverflow.
<?php
// Create file data.csv with your data
$handle = fopen('Sub-Companies.csv', 'r');
$customer_id = array();
$xyz_array = array();
// ...
// Better use a specified length (second parameter) instead of 0
// It slows down the whole process of reading the data!
while (($line = fgetcsv($handle, 0, ';')) !== FALSE) {
$customer_id[] = $line[0];
$xyz_array[] = $line[1];
}
I have a csv file that has like 30,000 rows in it. It also has like 9 columns. In the interest of speeding up the processing of everything I want to reduce the file to the two columns that I need and remove the rest. here is what I have done.
$retardment=1;//17;// 151; //499;// 991;// 1877
if (($handle = fopen($source, "r")) !== FALSE) {
$stock_handle = fopen($source_stock, "w+");
$row=0;
$col=array();
while (($line = fgetcsv($handle, 100000, ",")) !== FALSE) {
unset($line[1]);
unset($line[2]);
unset($line[3]);
unset($line[4]);
unset($line[5]);
unset($line[6]);
unset($line[8]);
unset($line[9]);
if($row%$retardment<1){
fputcsv($stock_handle, $line);
}
unset($line);
$row++;
}
fclose($handle);
fclose($stock_handle);
}
I am coping it to a new file and this works... but it seems to be pretty slow. Any ideas on how to make it faster? Thank you for the help.
Cheers -Jeremy
{EDIT}
So far this seems to take just as long. But works just fine
while (($line = fgetcsv($handle, 100000, ",")) !== FALSE) {
if($row%$retardment<1){
fputcsv($stock_handle, array($line[0],$line[7]));
}
$row++;
}
You could replace those unset() calls with...
$line = array($line[0], $line[7]);
Alternatively, remember that unset() takes multiple arguments...
unset($line[1], $line[2], ...);
You can speed it up fractionally more, but again it's a microtime()-measurable improvement: perception is that it won't be noticeably faster.
while (($line = fgetcsv($handle, 100000, ",")) !== FALSE) {
if($row++ % $retardment < 1){
fputcsv($stock_handle, array($line[0],$line[7]));
}
}
but as your script is IO-bound, it's the actual reads and writes that are the slowest functions, and you can't speed those up.
Using stream_copy_to_stream() with a stream input filter might be another approach, but you won't see much noticeable improvement unless you can reduce disk access times
I have a php code that will read and parse csv files into a multiline array, what i need to do next is to take this array and let simplehtmldom fire off a crawler to return some company stocks info.
The php code for the CSV parser is
$arrCSV = array();
// Opening up the CSV file
if (($handle = fopen("NASDAQ.csv", "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row $data is the variable for each line of the array
$c = count($data);
//Populate the array
for ($x=0;$x<$c;$x++) {
$arrCSV[$key][$x] = $data[$x];
}
$key++;
} // end while
// Close the CSV file
fclose($handle);
} // end if
echo "<pre>";
echo print_r($arrCSV);
echo "</pre>";
This works great and parses the array line by line, $data being the variable for each line. What i need to do now is to get this to be read via simplehtmldom, which is where it breaks down, im looking at using this code or something very similar, im pretty inexperienced at this but guess i would be needing a foreach statement somewhere along the line.
This is the simplehtmldom code
$html = file_get_html($data);
$html->find('div[class="detailsDataContainerLt"]');
$tickerdetails = ("$es[0]");
$FileHandle2 = fopen($data, 'w') or die("can't open file");
fwrite($FileHandle2, $tickerdetails);
fclose($FileHandle2);
fclose($handle);
So my qyestion is how can i get them both working together, i jave checked out simplehtmldom manual page several times and find it a littlebit vague in this area, the simplehtmldom code above is what i use in another function but by direclty linking so i know that it works.
regards
Martin
Your loop could be reduced to (yes, it's the same):
while ($data = fgetcsv($handle, 0, ',')) {
$arrCSV[] = $data;
}
Using SimpleXML instead of SimpleDom (Since it's standard PHP):
foreach ($arrCSV as $row) {
$xml = simplexml_load_file($row[0]); // Change 0 to the index of the url
$result = $xml->xpath('//div[contains(concat(" ", #class, " "), " detailsDataContainerLt")]');
if ($result->length > 0) {
$file = fopen($row[1], '2'); // Change 1 to the filename you want to write to
if ($file) {
fwrite($file, (string) $result->item(0));
fclose($file);
}
}
}
that should do it if I understood correctly...