I'm confused. I have problem how to add more than one line in csv archive.
In $V I collect datas from some conditions. Then I count how many datas are collected $countLm++.
The following code is my last try.
if ($V >= "1") {
$countLm++;
echo "Time:" . $row['DayTime'];
echo "|| AvT :". round ($row['Val(1)'],2);
echo " *C";
echo "|| ALM :". round ($row['Val(2)'],2);
echo "|| LM :" .round ($V, 2);
echo " % ";;
echo "<br />";
$sumT += (round ($row['Val1'])'],2));
$averageT = $sumT / $countLm ;
$csvFile = "saving path";
$handle = fopen($csvFile, "w");
if ($handle === false) {
exit("Error creating $csvFile");
}
fputcsv($handle, ['DayTime','AvT','ALM','LM']);
fputcsv($handle, [$row['DayTime'], round ($row['Val(1)'],2),round ($row['Val(2)'],2), round ($V, 2)]);
fclose($handle);
}
The problem is that I can "print" only one line in CSV. But I want to "print" more lines, as lines as $countLm is.
How can I add more lines? What can I modify?
Thanks for your advices!!!!!
Related
I know this question has been asked before but my problem is different because I need to return the specific rows after a search.
Basically, this is the scenario:
I need to search a CSV file for a specific word/string in the name column and then IF the word/string is found I need to get the row[4] and row[5] and print them in the PHP.
The CSV looks like this:
"id","ident","type","name","latitude_deg","longitude_deg","elevation_ft"
6523,"00A","heliport","Heliport",40.07080078125,-74.93360137939453,11,
So basically, I need to search by name and if found, return the latitude_deg,longitude_deg.
This is what I have so far... However, this searches the ENTIRE CSV file which makes it slightly slower and it only returns whether the CSV file contains the string/word or not...
$search = "Heliport";
$lines = file('myCsv.csv');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE);
}
if($line_number){
echo "Results found for " .$search
} else {
echo "No results found for $search";
}
Could someone please advice on this issue? Thanks in advance.
fgetcsv is a good tool for this, it reads a CSV line and breaks it into an array.
$search = 'Heliport';
if (($fp = fopen("myCsv.csv", "r")) !== false) {
while (($row = fgetcsv($fp)) !== false) {
if($row[3] === $search) {
echo 'Found ' . $row[3] . ': ' . $row[4] . ', ' . $row[5] . "\n";
}
}
fclose($fp);
}
I'm reading a text file of email addresses and outputting the domain only (with the # symbol). I need to alphabetize the list and then output to display on screen
Here is my code thus far:
<?php
$file_handle = fopen("file.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$parts = explode("#", $line);
$Id = $parts[count($parts) - 1];
echo "#" . $Id . "<br>";
}
fclose($file_handle);
?>
How can I initiate a sort to alphabetize the list?
This should work for you:
(Here I just get every line of the file with file(). Then I go through each line with array_map() where I only return the domain into the array $lines. At the end I sort the array with sort() and print it)
<?php
$lines = array_map(function($v){
return "#" . explode("#", $v)[1];
}, file("test.txt"));
sort($lines);
foreach($lines as $line)
echo $line . "<br />";
?>
Example input/output:
a.b#x.com
a.c#a.de
e.s#b.cu
#a.de
#b.cu
#x.com
I am trying to import data from a source that is not a csv or txt but I am able to read it like a text / csv with my code.
The problem I am having is that some "data records" do not follow the same logic. I have approximately 70% of the document conforming, however, I think I may be missing something in the data that is throwing off the results.
I would appreciate it if you could please take a look at the code and the file and help me figure out why some of the data is not working like the rest of the document. I suspect it is because of odd number of characters (~ and/or >) in one of the fields or that the start/stop is slightly different for some of the records.
<?php
header("Content-Type:text/html");
$file = "data.txt";
if (($handle = fopen($file, "r")) !== FALSE)
{
fgetcsv($handle, 1000, ">~Yn");
$imports = array();
while (($data = fgetcsv($handle, 1000, ">")) !== FALSE)
{
if(strpos($data[4],'<') !== false)
{
echo "<br /><strong>Section:</strong> " . $data[5];
echo "<br /><strong>Row:</strong> " . $data[6];
echo "<br /><strong>Qty:</strong> " . $data[7];
echo "<br /><strong>Price:</strong> " . $data[8];
echo "<br /><strong>Notes:</strong> " . $data[10];
}
else
{
echo "error: ";
print_r($data);
}
echo "<br /><br /><br /><br />";
}
fclose($handle);
}
?>
The sample data can be found here: Sample Data
I have found a solution that works better than the method I originally attempted. I first determined that loading it as a CSV was not giving me the best results. I then realized that there are common delimiters between each record that I was missing. That being said, I split the contents into lines and then split the lines into pieces using split(). I also ignored the first and last match because of data mismatches.
$file = "data.txt";
$content = file_get_contents($file);
$lines = split(">~", $content);
foreach($lines as $line)
{
$data = split(">", $line);
if(strpos($data['5'],'.') !== false) //if the section is a price
{
//the first match is ignored
}
elseif(empty($data['7'])) //if Qty is empty
{
//the last match is ignored
}
else
{
echo "<br><br><br>";
echo $data['5'] . " (Section) <br>";
echo $data['6'] . " (Row) <br>";
echo $data['7'] . " (Qty) <br>";
echo $data['8'] . " (Price) <br>";
//use the data
}
}
This resulted in a much more accurate and thorough data collection!
I am a newbie to php and have been searching tirelessly for a solution to this problem (i'll bet its a super simple solve too *sigh).
I am importing a .csv feed from a google doc. It is pulling in 2 columns, one for "name" and the other "location". I would like to remove duplicate "locations". since i am using fgetcsv, my understanding is that it is already sorting the data into an array. Ideally, it would omit the "location" duplicates so that the "names" look as though they are listed under the "location" they correspond to.
Here is what i have:
$url = "https://docs.google.com/spreadsheet/pub?key=0AsMT_AMlRR9TdE44QmlGd1FwTmhRRkFHMzFTeTZhS3c&output=csv";
$handle = fopen($url, "r");
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
echo "<li>\n";
echo $data[1];
echo "<br/>\n";
echo $data[2];
echo "</li>\n";
}
fclose($handle);
ideally i would be able to use something like this:
$url = "https://docs.google.com/spreadsheet/pub?key=0AsMT_AMlRR9TdE44QmlGd1FwTmhRRkFHMzFTeTZhS3c&output=csv";
$handle = fopen($url, "r");
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
echo "<li>\n";
echo array_unique($data[1]);
echo "<br/>\n";
echo $data[2];
echo "</li>\n";
}
fclose($handle);
Many thanks in advance for any help! :o)
This may work, assuming that the items in the array are grouped by location. It stores the last data item (location) and compares whether each item has that location. If it does, it prints it, otherwise it creates a new list item with the new location, and then prints the name underneath (I haven't tested it though):
$url = "the-url-to-my-csv-feed";
$handle = fopen($url, "r");
$lastdata = '';
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
if ($lastdata == '') {
echo "<li><strong>" . $data[1] . "</strong>\n";
echo "<br/>\n";
$lastdata = $data[1];
}
if ($lastdata != $data[1]) {
echo "</li>\n";
echo "<li><strong>" . $data[1] . "</strong>\n";
echo "<br/>\n";
$lastdata == $data[1];
}
echo $data[2] . "<br/>\n";
}
fclose($handle);
<? //PHP 5.4+
$url = 'url to your csv feed';
//Group people by same location first,
//not assuming csv is already sorted.
$namesByLocations = [];
//Because we're using \SplFileObject, when the reference goes out
//of scope at the end of the loop, the file pointer is never
//left open. This is true even if an exception is thrown
//in the middle of looping.
foreach(
\call_user_function(static function() use ($url){
$file = new \SplFileObject($url);
$file->setFlags(\SplFileObject::READ_CSV);
return $file;
})
as $array
){
//$array[1] is assumed to be location string
//$array[2] is assumed to be a name that is there.
$namesByLocations[$array[1]][] = $array[2];
}
foreach($namesByLocations as $location => $names){
//Protect against injection flaws,
//escape to destination's context. (html this time)
echo '<strong>' . \htmlspecialchars($location) . '</strong>';
echo '<ul>';
foreach($names as $name){
echo '<li>' . \htmlspecialchars($name) . '</li>';
}
echo '</ul>';
}
?>
Lets say the text file " data1.txt" contains:
56715||Jim||Green||19
5678||Sara||Red||92
53676||Mark||Orange||6
56787||Mike||Purple||123
56479||Sammy||Yellow||645
56580||Martha||Blue||952
ect...
.
.
I would like to echo only the line beginning with "5678||". "5678" is the exact $refVal or reference value. The line should display like this:
My name is: $nameVar
My color is: $colorVar
My number is: $numVar
Thanks...
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgetcsv($fh, 0, '||')) {
if ($line[0] == 5678) {
echo <<<EOL
My name is: $line[1]
My color is $line[2]
My number is $line[3]
EOL;
break; // if there's only ever one '5678' line in the, get out now.
}
}
fclose($fh);
alternate version, as suggested by Jared below. Probably will be faster, as it only does the array creation on the line that actually matches, and not for each line as the fgetcsv version does.
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgets($fh)) {
if (strpos($line, '5678||') === 0) { // only if right at start of string
$data = explode('||', $line);
echo <<<EOL
my name is blah blah blah
EOL;
break;
}
}
You can split each line into an array using explode, like so:
foreach ($lines as $line)
{
$t = explode('||', $line);
if ($t[0] == $refVal) {
// echo the rest of $t array however you want
// $t[1] would be the name, $t[2] the color, etc
}
}