Read txt file into HTML table - html

I have to read a txt file into a HTML table.
There are many fields in it but I only want to read the field that says "value".
Here is my txt file:
one=availability:, timestamp=90754, value=no
two=description:, timestamp=074693, value=not sure
three=Name, timestamp=90761, value=yes
The one, two, three values are my row headers and I want it to display the values underneath.
Is there anyway of doing this using iframe?? PHP is not working for me.

Supposing the value is always the last field and you are reading the file line by line I would use a dirty approach:
$value = explode('value=', $line)[1];

longwinded approach
$headers=[];
$values=[];
$lines = file('./homework.txt', FILE_IGNORE_NEW_LINES);
foreach($lines as $line){
$chunks = explode(',',$line);
foreach($chunks as $index => $chunk){
list($key, $value) = explode('=', trim($chunk));
if(!$index){
$headers[] = $value;
}
if('value' === $key){
$values[] = $value;
}
}
}
echo "<table><thead><tr>";
foreach($headers as $h){
echo "<th>{$h}</th>";
}
echo "</tr></thead><tbody><tr>";
foreach($values as $v){
echo "<td>{$v}</td>";
}
echo "</tr></tbody></table>";

If all rows follow the same pattern you can probably use:
//$textfilestring = "one=availability:, timestamp=90754, value=no
//two=description:, timestamp=074693, value=not sure
//three=Name, timestamp=90761, value=yes";
$textfilestring = file_get_contents("PATH_TO_FILE");
$arraylines = explode("\n", $textfilestring);
for ($i=0;$i<count($arraylines);$i++) {
$arraylines[$i] = explode("value=", $arraylines[$i]);
}
echo "<pre>";
var_dump($arraylines);
echo "</pre>";
echo $arraylines[0][1] . "<br>";
echo $arraylines[1][1] . "<br>";
echo $arraylines[2][1] . "<br>";
$arraylines should be twodimensional with one part beeing
one=availability:, timestamp=90754,
and one beeing
no
Not tested though.

Related

Getting data from database using part of the URL as a value - PHP

My url type is like "http://localhost/boardgame/profile/Duncan/" the last word is the user name...
I just try to get some data from database and I need a user name to do this. I tried to get it from page URL but it doesn't work. Where did I go wrong? What has to be done? I'll be greateful if anybody can help...
<?php
$actual_link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//echo $actual_link;
$rest = substr($actual_link, 35, -1);
echo $rest;
$link = mysqli_connect("localhost", "root", "", "bgt");
if (mysqli_connect_error()) {
die ("Veritabanı bağlantısında hata var");
} if (($rest) !="") {
if (get_current_user_id($link) == '0') {
echo "<p>Kullanıcının koleksiyonunu görebilmek için giriş yapmanız
gerekiyor.</p>";
} else {
$query = "SELECT TITLE FROM wp_user_collections WHERE `user_name` =
'".mysqli_real_escape_string($link, $rest)."'";
echo "<div><h1>'".mysqli_real_escape_string($link, $rest)."'in
Koleksiyonu</h1><div>";
if($result = mysqli_query($link, $query)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>Oyun Adı</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>'" . $row['TITLE'] . "'</td>";
echo "</tr>";
}
echo "</table></div>";
}
}
}
} else {
echo "Kullanıcının koleksiyonunu görebilmek için <a
href='http://localhost/boardgame/profile/'".mysqli_real_escape_string($link,
$rest)."'>tıklayınız</a>";
}
?>
Here is the solution I have thought...using array then extracting the last element (or second last since there is a trailing '/' slash which is a delimiter)
$uri="http://localhost/boardgame/profile/Duncan/";
$uriParts=explode('/', $uri); //converts the uri string into an array of words separated by forward slash
$name=$uriParts[sizeOf($uriParts)-1-1]; //the user name comes from 2nd last item as the last item is empty
echo $name;
I could suggest you use Regular Expression to extract the user name, however I'm not well versed with it yet.

itunes search store api

I want to get data from the API iTunes Store to my PHP file. In the search form you can fill the artist and title of the song. I want to show only the data from the song. This is my code:
$title = $_POST["title"];
$artist = $_POST["artist"];
$query_string = urlencode($title);
$query_string2 = urlencode($artist);
$json = file_get_contents('https://itunes.apple.com/search?term=$query_string&term=$query_string2'); // this WILL do an http request for you
$data = json_decode($json);
echo "<div class='container' id='movies'>";
echo "<div class='col-md-4' id='movie'>";
echo "<img src='" .$data->artworkUrl60. "' width='200'>";
echo "<h4>" .$data->artistName. " - " .$data->trackName. "</h4>";
i get this error: Notice: Undefined property: stdClass::$artworkUrl60 in....
Whats wrong with my code?
Because your $data Object doesn't contain an attribute named $artworkUrl60.
Your HTTP query doesn't not work correctly, you should use double quote instead of single quote.
// For limit you can add 'limit' parameter
$json = file_get_contents("https://itunes.apple.com/search?term=$query_string&term=$query_string2&limit=20");
// OR concatenation
// $json = file_get_contents('https://itunes.apple.com/search?term='.$query_string.'&term='.$query_string2);
$data = json_decode($json);
if (0 == $data->resultCount) {
echo 'No result found ! ';
}
else {
foreach ($data->results as $row){
echo "<div class='container' id='movies'>";
echo "<div class='col-md-4' id='movie'>";
echo "<img src='" .$row->artworkUrl60. "' width='200'>";
echo "<h4>" .$row->artistName. " - " .$row->trackName. "</h4>";
}
}
https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#searchexamples

How to repeat different pic?

I wan to always display the different pic. So there's a problem with looping the different pic. How do i do that?
index.php:
<?php
$result = mysql_query("SELECT * FROM table2", $connection );
echo '<ul>';
while($row = mysql_fetch_array($result)) {
if ($row)
echo "<li>";
echo "<img src='code.php?id=3'>";
echo "&nbsp";
echo "</p>";
echo "</li>";
echo "<br/>" ;
}
echo '</ul>';
mysql_close($connection);
?>
You need to pull the id value from the database. If you have a column called, maybe id you would want to put:
while($row = mysql_fetch_array($result)){
if ($row){
echo "<li>";
echo "<img src='code.php?id=".$row['id']."'/>"; // see what I did there?
echo "&nbsp";
echo "</p>"; // take this out
echo "</li>";
echo "<br/>"; // take this out
}
}
P.S. - don't write new code using the deprecated mysql extension. Use PDO or mysqli at least. And don't put <br />s between your <li>s, or close unopened <p>s. And, generally speaking, don't store your images in your database - just store the path to the image and put the images themselves in a folder on the server where they belong.
And please format your code - it is hard to read with no indentation or separation of files (your if statement was not properly enclosing what should have been conditioned statements). And mysql_real_escape_string is not as cool as you think it is.
Hope this helps.

return an element from array of json output

I am trying to extract specific values returned from google api
<?php
$url='http://maps.googleapis.com/maps/api/distancematrix/json?origins=19.1629924,72.83930190&destinations=19.1802370,72.8554149&sensor=false';
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
$array=json_decode($contents);
echo $array['rows']['elements']['distance']['value'];
?>
I expected the value of 4238 to be returned. Instead I get an error:
`PHP Fatal error: Cannot use object of type stdClass as array in test9.php on` line 7
Te correct solution is:
echo $array->rows[0]->elements[0]->distance->value;
Do the following to see the json:
<?php
$url='http://maps.googleapis.com/maps/api/distancematrix/json?origins=19.1629924,72.83930190&destinations=19.1802370,72.8554149&sensor=false';
$contents = file_get_contents($url);
$contents = utf8_encode($contents);
echo "<pre>";
echo $contents;
echo "\n";
echo "\n";
$array=json_decode($contents);
echo $array->rows[0]->elements[0]->distance->value;
?>
http://www.json.org/
have you tried node.js?
The following code solved the problem:
$array=json_decode($contents, true);
echo $array['rows'][0]['elements'][0]['distance']['value'];

How to convert mysql table data to Excel or CSV format in CakePHP?

I want to convert my sql data to csv files while clicking on a button. The code fragments I found for sql to CSV conversion were in PHP, and I'm trying to convert it to CakePHP since I'm working in CakePHP.
Here is the PHP code I'm tring to convert:
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
SOLUTION
Function in the Controller:
function exporttocsv()
{
$this->set('headers',$this->Result->find('all',array('fields'=>'Result.label')));
$this->set('values',$this->Result->find('all',array('fields'=>'Result.value')));
}
exporttocsv.ctp file:
<?php
foreach($headers as $header):
$csv_output .=$header['Result']['label'].", ";
endforeach;
$csv_output .="\n";
if(!empty($values)){
foreach($values as $value):
$csv_output .=$value['Result']['value'].", ";
endforeach;
$csv_output .="\n";
}
else{
echo "There is no data to export.";
}
$filename = "export_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
First of all, you don't do queries and output in the same file in Cake. You query the data as usual in the Controller, $this->set() the result to the view, and in the view you do something like this:
foreach ($results as $result) {
echo join(', ', $result['COLUMNS']);
echo "\n";
}
Outputs something like this:
value, varchar(25), NO, , ,
submitter, int(11), NO, , ,
...
Since Cake automatically wraps a layout around your view, you'll have to set the layout to something different, like 'ajax' (which is simply an empty layout).
deceze is correct about outputting the results from the view file. You'll just need to set some headers so that it appears as a file download on the client side. You can simply put these 2 calls in the top of your view:
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:attachment;filename=\"{$filename}\"" );
If you plan on doing csv downloads in more than one place in your application, I'd recommend this helper:
http://bakery.cakephp.org/articles/view/csv-helper-php5
I use it and it works well.