put echo into a variable with php - php

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.

Related

PHP Cron Read CSV from URL and Convert to Array

I am trying to develop email system that need to be send every month. So i need to build cron job file from php. Anyone know how to read file CSV or Excel file from url such as:
http://yourdomain.com/cron.php?file=http://google.com/monthly.csv
I am stuck when try to read file from url.
This is my recent code:
<?php
$url = 'http://www1.intranet.com/reportingtool.asp?settings=var&export=ok';
$tmpfname = tempnam(sys_get_temp_dir());
file_put_contents(
$tmpfname,
file_get_contents($url)
);
?>
If you're dealing with remote files, you should always keep in mind that
The connection between you and the remote can break, and you won't get the full file content;
The file can be too big to read it on-the-fly.
In both cases, file_get_contents() is not a very good thing to use: you should consider cURL functions for that. However, if the concerns above are negligible, you should be okay with the following (as the example here suggests):
$url = 'http://www1.intranet.com/reportingtool.asp?settings=var&export=ok';
$tmpfname = tempnam(sys_get_temp_dir());
file_put_contents(
$tmpfname,
file_get_contents($url)
);
if (($handle = fopen($tmpfname, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// Do something with $data, which comes in
// as an array of values from the current CSV line.
}
}
Someone would need one more example, so leaving it here:
$dataSource can be any file on drive or just online link to parse csv.
private array $data = [];
private string $dataSource = "https://any.csv";
if (($open = fopen($dataSource, 'rb')) !== false)
{
while (($data = fgetcsv($open, 1000, ";")) !== false)
{
$data[] = $data;
}
fclose($open);
}

Why is str_replace not working correctly

In my directory I have a list.csv of the form:
RP2015, active
Hope, paused
Process99, active
I'm writing a php script to allow a web user to switch the different lines from 'active' to 'paused' and back. Unfortunately I've hit a snag. My current code is live at: http://whitewaterwriters.com/Driver/index.php
and it looks like this
<HTML>
<Body>
<?
if ($_POST != null) {
$target = $_POST ['sprint'];
echo "<br>Target was:".$target;
$replacement=str_replace('active','paused',$target);
if (strpos($target,'paused') !== false) {
$replacement=str_replace('paused','active',$target);
}
echo "<br>Replacement was:".$replacement."<br>";
$filename = "list.csv";
$contents = file_get_contents($filename);
print "<br>contents was:".$contents;
$new_contents = str_replace($target, $replacement, $contents);
print "<br>contents became:".$new_contents;
file_put_contents($filename, $new_contents);
}
?>
<br><br>
<?php
$row = 1;
if (($handle = fopen("list.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo '<form action="index.php" method=post>';
echo $data[0] . $data[1];
echo '<button type="submit" value="'. $data[0].", ".$data[1].'" name="sprint">Pause</button></form><br>';
}
fclose($handle);
}
?>
</body>
</html>
For some reason the replace is not firing. The event is captured, the correct target and replace strings are (I think) generated, but the replace is NOT coming out. The output I get is:
Target was:RP2015, active
Replacement was:RP2015, paused
contents was:RP2015, active
contents became:RP2015, active
RP2015 active
Can anyone tell me what's going on?
EDIT:
The current list.csv is exactly:
RP2015, active
`
Try this:-
$fp = fopen($filename, "wb");
$handle = fopen($filename, "wb");
$replacement = str_replace("active", "paused", $fp);
$numbytes = fwrite($handle, $replacement);
fclose($handle);
The thing I had forgotten is that html squashes consecutive spaces together which is why the $target looked like it was fine. Actually:
$data[0].", ".$data[1]
only needed to be
$data[0].",".$data[1]
Because there was a space left over from the csv parsing. I'll make the code a bit more robust to that in future.
For the interested - this helper function I wrote helped me locate the error:
function toask($inStr){
$arr1 = str_split($inStr);
foreach ( $arr1 as $a){
print ord($a)." ";
}
}
It converts a string to a sequence of ascii codes do you can make sure, for example, that quote characters are the ones you think they are...

Run PHP function in While Loop

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.

Updating CSV Column Values Using UA-Parser Library

I'm using the ua-parser library to identify the device family for a number of user agent strings in a spreadsheet column. The problem I'm running into is that it doesn't seem like my function is really running. The value output for detectAgent($data[2]) is not always accurate.
Here's a code sample. I feel like I must be missing something related to the limitations of creating objects over and over again.
Thanks in advance for any help.
<?php
require_once 'vendor/autoload.php';
use UAParser\Parser;
function detectAgent($ua) {
$parser = Parser::create();
$result = $parser->parse($ua);
return $result->os->family;
}
$input_file = "input.csv";
$output_file = "output.csv";
if (($handle1 = fopen($input_file, "r")) !== FALSE) {
if (($handle2 = fopen($output_file, "w")) !== FALSE) {
while (($data = fgetcsv($handle1, 5000000, ",")) !== FALSE) {
// Alter your data
#print $data . "<br />";
$data[2] = detectAgent($data[2]); //identify browser family
// Write back to CSV format
fputcsv($handle2, $data);
}
fclose($handle2);
}
fclose($handle1);
}
?>
This was a silly mistake. I was writing to the wrong column in $data[2] = detectAgent($data[2]);.
If anyone else runs into the same problem, the code is working now and I've posted an example here.

Modify a csv file line by line

I have a big file that I want to modify every line in it.
I want to use PHP to do it quickly :
My file is CSV file ;
20010103,02,00,00,0.9496
20010103,03,00,00,0.9504
20010103,04,00,00,0.9499
I want to make it like this to be able to use it late with Highchart:
[Date.UTC(2001,01,03,02,00,00),0.9496],
[Date.UTC(2001,01,03,03,00,00),0.9504],
[Date.UTC(2001,01,03,04,00,00),0.9499],
How canI loop every line and make this modification ?
See the fgetcsv and fputcsv PHP functions. It will basically be something like:
if (($handle1 = fopen("input.csv", "r")) !== FALSE) {
if (($handle2 = fopen("output.csv", "w")) !== FALSE) {
while (($data = fgetcsv($handle1, 1000, ",")) !== FALSE) {
// Alter your data
$data[0] = '...';
// Write back to CSV format
fputcsv($handle2, $data);
}
fclose($handle2);
}
fclose($handle1);
}
Try this code:
<?php
$filename = 'info.csv';
$contents = file($filename);
foreach($contents as $line) {
$data = explode(",",$line);
$val = "[Date.UTC(".substr($data[0],0,4).",".(substr($data[0],4,2)).",".substr($data[0],6,2).",".$data[1].",".$data[2].",".$data[3]."),".$data[4]."],";
}
?>

Categories