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);
}
}
?>
Related
I would like to extract key value pair output from JSON formatted file using PHP and put into html table & database with exact key column. I tried code mentioned in Extract JSON ouput to get line by line key pair values using PHP but it doesn't work for multiple lines and gives wrong output from 2nd line onwards itself due to multiple lines from 2nd key.
As we discussed in that, filing separate question to avoid clutter the same question.
JSON file content:
{"key":"SEM-5765","status":"Closed","components":"UX","affectedVersions":"SEM 8.8.x","fixVersions":"SurmaZuse-8.8.10","customerFacingInfo":"[https://goog.ezy.com/show_bug.cgi?id=109021 Bug 109021] - Content spoofing (text) via loginErrorCode \[CWE-345\]"} {"key":"SEM-3325","status":"Closed","components":"UX","affectedVersions":"SEM Prior to 8.7","fixVersions":"SurmaZuse-8.8.10","customerFacingInfo":"Fixed a number of bugs related to Delegated Admin in the Admin Console:
* \"New administrator\" creation button was not disabled for delegated admin without required rights ([https://goog.ezy.com/show_bug.cgi?id=108503 Bug 108503])
* \"Account Limits\" in domain settings could not be shown even when adminConsoleDomainLimitsTabRights was added ([https://goog.ezy.com/show_bug.cgi?id=108327 Bug 108327])
* Had been unable to remove \"Dynamic Group\" from distribution properties page ([https://goog.ezy.com/show_bug.cgi?id=108499 Bug 108499])
* After performing a bulk migration, the Delegated Admin user encountered an `HTTP Error 403` when attempting to download the list of provisioned accounts ([https://goog.ezy.com/show_bug.cgi?id=108539 Bug 108539])"} {"key":"SEM-2755","status":"Closed","components":"UX","affectedVersions":"SEM Prior to 8.7","fixVersions":"SurmaZuse-8.8.10","customerFacingInfo":"Global Admin can now control the Downloads View (Admin > Tools > Download) and Help Center view for Delegated Admins."}
Expected:
SEM-5765
Closed
UX
SEM 8.8.x
SurmaZuse-8.8.10
[https://goog.ezy.com/show_bug.cgi?id=109021 Bug 109021] - Content spoofing (text) via loginErrorCode \[CWE-345\]
SEM-3325
Closed
UX
SEM Prior to 8.7
SurmaZuse-8.8.10
Fixed a number of bugs related to Delegated Admin in the Admin Console: * \"New administrator\" creation button was not disabled for delegated admin without required rights ([https://goog.ezy.com/show_bug.cgi?id=108503 Bug 108503]) * \"Account Limits\" in domain settings could not be shown even when adminConsoleDomainLimitsTabRights was added ([https://goog.ezy.com/show_bug.cgi?id=108327 Bug 108327]) * Had been unable to remove \"Dynamic Group\" from distribution properties page ([https://goog.ezy.com/show_bug.cgi?id=108499 Bug 108499]) * After performing a bulk migration, the Delegated Admin user encountered an `HTTP Error 403` when attempting to download the list of provisioned accounts ([https://goog.ezy.com/show_bug.cgi?id=108539 Bug 108539])
SEM-2755
Closed
UX
SEM Prior to 8.7
SurmaZuse-8.8.10
Global Admin can now control the Downloads View (Admin > Tools > Download) and Help Center view for Delegated Admins.
Tried code:
echo "<table class='table create-release-note-table'>
<thead>
<tr><th>#</th><th>Ticket ID</th><th>Status</th><th>Components</th><th>Affected Versions</th><th>Fix Versions</th><th>Description</th></tr>
</thead>
<tbody>";
$i = 0;
$resultFile = fopen($resultURL, "r");
#$lines = file($resultURL, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
#print_r ($lines);
#exit;
while (!feof($resultFile)) {
$line = trim(fgets ($resultFile));
$line = str_replace("\\\"", "", $line);
$line = stripslashes($line);
$lineArray = json_decode($line, true);
echo "<tr><td>" . ++$i . "</td>";
parseData($lineArray);
echo "</tr>";
}
echo "</tbody></table>";
fclose ($resultFile);
// Parse release note data
function parseData($array) {
$value = str_replace(",", ";", $value);
foreach ($array as $key => $value) {
if (is_bool($value)) {
echo ("<td>" . $value? 'true' : '') . "</td>";
} else {
echo "<td>" . $value . "</td>";
}
}
}
Your JSON seems not be formatted well in first place. You missed commas and square brackets.
This is a very basic solution but you can correct your JSON following this method:
Add commas
$json = str_replace("} {", "}, {", $original_json);
Clean a bit the code (this is rough. Good for your case but not the best at all!)
$json = str_replace("\[", "[", $json);
$json = str_replace("\]", "]", $json);
Wrap it inside [ ]
$your_json_string = "[" . $json . "]";
and then you can just use
$json_parsed = json_decode($your_json_string);
and
echo "<table class='table create-release-note-table'>
<thead>
<tr>
<th>#</th>
<th>Ticket ID</th>
<th>Status</th>
<th>Components</th>
<th>Affected Versions</th>
<th>Fix Versions</th>
<th>Description</th>
</tr>
</thead>
<tbody>";
foreach($json_parsed as $json_object){
echo "<tr>";
echo "<td></td>";
echo "<td>" . $json_object->key . "</td>";
echo "<td>" . $json_object->status. "</td>";
echo "<td>" . $json_object->components. "</td>";
echo "<td>" . $json_object->affectedVersions. "</td>";
echo "<td>" . $json_object->fixVersions . "</td>";
echo "<td>" . $json_object->customerFacingInfo . "</td>";
echo "</tr>";
}
echo "</tbody>
</table>";
That's it
I'm afraid the issue is on the json file side.
If I understand correctly, the JSON file content exposed in your question is supposed to be a single json file.
If so, the format of the json seems incorrect.
Your json is structured as follow (I remove some parts of the content to help clarify my point):
{"key":"SEM-5765"}
{"key":"SEM-3325"}
{"key":"SEM-2755"}
Which is not a single json, but 3 differents jsons on a single file.
A correct json structure would have been:
[
{"key":"SEM-5765"},
{"key":"SEM-3325"},
{"key":"SEM-2755"},
]
Which is an array of json and a correct json structure.
So I think you have two possibilities :
you can correct the json structure
you can read your file by separating each line and traited each line as a single json
Either way, you will have to add a step to your code to loop through each line/json entity
In your case you can use explode and implode php function to get your desire output.
I have added few code lines :
$lineExplode = explode('}',$line);
$line = implode(',',$lineExplode);
$lineArray = json_decode("[".$line."]", true);
All other code is the same as your example:
<?php
echo "<table class='table create-release-note-table'>
<thead>
<tr><th>#</th><th>Ticket ID</th><th>Status</th><th>Components</th><th>Affected Versions</th><th>Fix Versions</th><th>Description</th></tr>
</thead>
<tbody>";
$i = 0;
$resultFile = fopen($resultURL, "r");
#$lines = file($resultURL, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
#print_r ($lines);
#exit;
while (!feof($resultFile)) {
$line = trim(fgets ($resultFile));
$line = str_replace("\\\"", "", $line);
$line = stripslashes($line);
$lineExplode = explode('}',$line);
$line = implode(',',$lineExplode);
$lineArray = json_decode("[".$line."]", true);
echo "<tr><td>" . ++$i . "</td>";
parseData($lineArray);
echo "</tr>";
}
echo "</tbody></table>";
fclose ($resultFile);
// Parse release note data
function parseData($array) {
$value = str_replace(",", ";", $value);
foreach ($array as $key => $value) {
if (is_bool($value)) {
echo ("<td>" . $value? 'true' : '') . "</td>";
} else {
echo "<td>" . $value . "</td>";
}
}
}
?>
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 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 currently have php generating a table from csv. I use tags to identify columns, which i later use jquery and datatables to sort, filter, and highlight.
I am looking for a way to make the data from a column into links. the data is case numbers and there is a predefinited link, you would just added the case number to the end of it and that would be your link to another page.
Do anyone know how I can achieve this, I'll include a snippet below so you can get an idea of how the table is created.
<th>ASUP Created Flag</th>
</tr>
</thead>
<tbody>
END;
//here we open the csv file as read-only
$f = fopen("cases.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
//this starts the alternation of tr and td for building the table
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
//after the table has been built, this is where we close it out
echo "\n</tbody></table></section></div></body></html>";
?>
Are you asking for something like:
<th>ASUP Created Flag</th>
or for the actual cell data:
foreach ($line as $cell) {
echo "<td><a href='some url'>" . htmlspecialchars($cell) . "</a></td>";
}
If you're wondering what some url should be, well that's completely up to you. If it depends on the cell data, then you would need some way to reference a URL given the cell data (either through a lookup array, database table, just some way to associate a URL with the value in $cell).
Update
If you want your case numbers to be links, and the value of the cell is the exact value you want to use in the URL, you can do something like this:
$count = 0;
foreach ($line as $cell) {
$cell = htmlspecialchars($cell);
if($count == 0) {
echo "<td><a href='/case/" . $cell . "'>" . $cell . "</a></td>";
} else {
echo "<td>" . $cell . "</td>";
}
$count++;
}
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>';
}
?>