Reading contents from text/csv document with inconsistencies in data - php

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!

Related

php add more than one lines in csv

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!!!!!

Creating a PHP Page to Search a CSV

I have a CSV that is appended every 10 minutes with Data that looks similar to
07-01-2020 10:40 https://www.google.com OK 0.080382
07-01-2020 10:40 https://www.yahoo.com OK 0.120117
The first column being date shown as 07-01-2020 in this example,
time represented by the 10:40, Link represented by https://www.google.com, Status represented by OK and latency represented by 0.080382
I currently have all the results being displayed with the following bit of code:
<?php
$file = fopen("resultsTime.csv", "r");
//Output lines until EOF is reached
while(! feof($file)) {
$line = fgets($file);
echo $line. "<br>";
}
fclose($file);
?>
This works perfectly fine as it should. However I am looking to instead enter say https://www.google.com into a text box and get the history for that site. An additional piece for that would be I only want when the status is not OK.
Hopefully that is well enough explained. I have seen some examples on here but none that offer enough detail to be able to create my own.
Thank you for your help.
Indents are a little messy here but this is the solution I came up with that works great.
Should be easily modifiable if others are looking to do the same
<center>
<form action="" method="POST">
<label>Site</label><input type="text" name="search">
<input type="submit" name="submit" value="search">
</form>
</center>
<center>
<?php
if (isset($_POST['submit'])) {
$word = $_POST['search'];
print "<tr><td><u>Date</u><td><u>Time</u></td><td><u>Site</u></td><td><u>Status</u></td><td><u>Latencey</u></td></tr>";
if (($h = fopen("resultsTime.csv", "r")) !== FALSE) {
// Convert each line into the local $data variable
while (($data = fgetcsv($h, 1000, ",")) !== FALSE) {
foreach ($data as $str) {
$site = explode(" ", $str);
if ($site[3] != "OK" && $site[2] == $word) {
print "<tr><td>" . $site[0] . "</td>";
print "<td>" . $site[1] . "</td>";
print "<td>" . $site[2] . "</td>";
print "<td>" . $site[3] . "</td>";
print "<td>" . $site[4] . "</td></tr>";
}
}
}
// Close the file
fclose($h);
}
}
?>

Search CSV file and then Return specific rows from CSV file using PHP?

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);
}

php: using google csv, remove duplicate values populated in column

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>';
}
?>

PHP: problems searching text in a file

I think i was doing halfway good to get this to halfway work. Anyways the following code works to find it on the first line, but i have a script that creates each on an individual line.
Please revise or create a completely new version of the following to make it to search for the form data on every line.
$search = $_POST['search'];
$file = file("SLIST.txt");
foreach($file as $line)
{
$line = trim($line);
if($line == $search)
{
echo $search . " WAS found in the database";
}
else
{
echo $search . " was NOT found in the database";
}
}
by form i mean there is a search form on the previous page. This page is the page where it tells you whether the text put into the search form matches a line in the file (ex: Line 1: BOOT Line 2: Tree Search entry: Tree Echo msg: Tree WAS found in the database.)
It is currently not working like i intended.
If you only want to know if the search string was in the file, and don't care on which line, then strpos() (doc) with file_get_contents() might be for you like this:
$file = file_get_contents('SLIST.txt');
$search = $_POST['search'];
if (strpos($file,$search)){
echo $search . " WAS found in the database";
}
else
{
echo $search . " was NOT found in the database";
}
If you want to know the line, your solutions should work as well if you change the if($line == $search) with my strpos().
If the line has to be exactly the search query you are looking for, then your solution should work just fine
It isn't so clear. I suppose the following is what you wanted.
<?php
$search = $_POST['search'];
$file = file("SLIST.txt");
$found = false;
foreach($file as $line) {
$line = trim($line);
if($line == $search) {
$found = true;
break;
}
}
if ($found)
{
echo $search . " WAS found in the database";
}
else {
echo $search . " was NOT found in the database";
}
?>
Are you looking to find a single string in an entire file. i know you want to look on every line but this is more efficient.
Try this
$file = file_get_contents("SLIST.txt");
if(strpos($file, $search))
{
echo $search . " WAS found in the database";
}
else {
echo $search . " was NOT found in the database";
}
If you just want to read lines then do
if(strpos($line, $search))
{
echo "found";
}
else
{
echo "not found";
}

Categories