Undefined offset issue in explode - php

Firstly I apologise for asking a question which must be somewhat rookie or simple, but I cannot seem to find any code that I've researched to solve my problem.
Notice: Undefined offset: 1 in C:\Users\Joshua\Desktop\USBWebserver v8.5\8.5\root\Assignment\Table.php on line 14
This error continues from Offset 1 - 7.
The code that I am currently using to pull the data from the CSV file is as follows:
<?php
$fp = fopen ("quotes.csv","r");
if (!$fp) {echo "<p>Unable to open remote file.</p>"; exit;}
?>
<table>
<tr><th>ID</th> <th>Price</th> <th>Volume </th></tr>
<?php
$i=0;
while (!feof($fp)):
$line = fgets($fp, 2048);
$out[$i] = array($line);
list ($ID, $Price, $StockDate, $StockTime, $Change, $DayHI, $DayLOW, $Volume,) = explode(",", $out[$i][0]);
echo "<tr><td>$ID</td> <td>$Price</td> <td>$StockDate </td><td>$StockTime</td> <td>$Change</td> <td>$DayHI</td> <td>$DayLOW</td> <td>$Volume</td></tr>";
$fp++;
$i++;
endwhile;
?>
</table>
<?php
//echo "<p>".$out[0][0]."</p>";
//echo "<p>".$out[1][0]."</p>";
//echo "<p>".$out[2][0]."</p>";
fclose($fp);
?>
I'm unsure as to how something is undefined as the correct number of values are being called from the CSV.
I understand this isn't a site to teach someone PHP basics but any advice would be appreciated to help solve the problem, I would be appreciative!

I think you didn't want to +1 on file pointer:
$fp++;
Removing this line should do the trick.
UPDATE:
You should also check fgets if it's not false, because it means end of file:
$line = fgets($fp, 2048);
if($line === false) break;
Fully working example:
<?php
$fp = fopen ("quotes.csv","r");
if (!$fp) {echo "<p>Unable to open remote file.</p>"; exit;}
?>
<table>
<tr><th>ID</th> <th>Price</th> <th>Volume </th></tr>
<?php
$out = array();
$i=0;
while (!feof($fp)):
$line = fgets($fp, 2048);
if($line === false) break;
$out[$i] = array($line);
list ($ID, $Price, $StockDate, $StockTime, $Change, $DayHI, $DayLOW, $Volume) = explode(",", $out[$i][0]);
echo "<tr><td>$ID</td> <td>$Price</td> <td>$StockDate </td><td>$StockTime</td> <td>$Change</td> <td>$DayHI</td> <td>$DayLOW</td> <td>$Volume</td></tr>";
$i++;
endwhile;
?>
</table>
<?php
echo "<p>".$out[0][0]."</p>";
fclose($fp);
Last echo gave me my first string line from .csv.

Try making a single variable for the exploded values and check if the variable contains all the data
$temporal_var = explode(",", $out[$i][0]);
print_r($temporal_var);

Do you have initialized the $out array? moreover for what i see you don't need the $i index since you can just call $out[] = array($line); to append an element to the array

Try this approach, using the native php CSV handler:
<?php
// Set a list of headers
$ths[0] = 'ID';
$ths[1] = 'Price';
$ths[2] = 'StockDate';
$ths[3] = 'StockTime';
$ths[4] = 'Change';
$ths[5] = 'DayHI';
$ths[6] = 'DayLOW';
$ths[7] = 'Volume';
// Open the file with error handling
$fp = fopen('quotes.csv', 'r');
if( !$fp ) { die('<p>Unable to open remote file.</p>'); }
// Get the size
$fz = filesize('quotes.csv') + 1;
// Create a Data holder array
$fpData = array();
// While there is a line. Use native fgetcsv()
while ( $fpRow = fgetcsv( $fp, $fz, ',' ) ) {
// For each element in the row we asign it to its header
for ($i=0; $i < count($fpRow); $i++) {
$thisRow[ $ths[$i] ] = $fpRow[ $i ];
}
// Append to the Data array
$fpData[] = $thisRow;
}
// Close the file
fclose($fp);
// Test the output
// print_r( $fpData );
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get CVS</title>
</head>
<body>
<table>
<thead>
<tr>
<?php foreach ($ths as $thisField): ?>
<th><?php echo $thisField ?></th>
<?php endforeach ?>
</tr>
</thead>
<tbody>
<?php foreach ($fpData as $thisItem): ?>
<tr>
<td><?php echo $thisItem['ID'] ?></td>
<td><?php echo $thisItem['Price'] ?></td>
<td><?php echo $thisItem['StockDate'] ?></td>
<td><?php echo $thisItem['StockTime'] ?></td>
<td><?php echo $thisItem['Change'] ?></td>
<td><?php echo $thisItem['DayHI'] ?></td>
<td><?php echo $thisItem['DayLOW'] ?></td>
<td><?php echo $thisItem['Volume'] ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</body>
</html>

Related

How can i parse this json file in php? [duplicate]

This question already has answers here:
json_decode to array
(12 answers)
Closed 3 years ago.
I want to parse this json in php and show it in a table.
{"Files":[{"name":"Tester","Dir":true,"path":"\/stor\/ok"},{"name":"self","Dir":true,"path":"\/stor\/nok"}]}
You can use simple foreach loop like this.
Code
<?php
$json = '{"Files":[{"name":"Tester","Dir":true,"path":"/stor/ok"},{"name":"self","Dir":true,"path":"/stor/nok"}]}';
$json = json_decode($json, true);
?>
<!DOCTYPE html>
<html>
<body>
<table border="1">
<tr><td>name</td><td>Dir</td><td>path</td></tr>
<?php foreach ($json["Files"] as $k => $v): ?>
<tr>
<td><?php echo htmlspecialchars($v["name"]); ?></td>
<td><?php echo htmlspecialchars($v["Dir"]); ?></td>
<td><?php echo htmlspecialchars($v["path"]); ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
Result
I created you some little code example. You decode your string to json array. Thereafter you can parse the Files array with a foreach loop. Then in the foreach you can output/ save your values. In this case I output the name.
$string = '{"Files":[{"name":"Tester","Dir":true,"path":"\/stor\/ok"},{"name":"self","Dir":true,"path":"\/stor\/nok"}]}';
$string = json_decode($string, true);
if ($string != null)
{
foreach ($string['Files'] as $values)
{
echo $values['name'];
echo "\n";
}
}
Output:
Tester
self

Fetching JSON data from a url through PHP

I am trying to use php to make a currency converter. However as you see, everything works if I locally download the JSON, re-structure it and call it through file_get_contents().
JSON:
{"status":true,"data":[{"buy_rate":"19.00","sell_rate":"19.20","currency":"China Yuan","flagicon":"CN","countrycode":"CNY"},{"buy_rate":"1.13","sell_rate":"1.14","currency":"Japanese Yen","flagicon":"jp","countrycode":"JPY"},{"buy_rate":"166.00","sell_rate":"167.65","currency":"UK Pound Sterling","flagicon":"GB","countrycode":"GBP"},{"buy_rate":"33.70","sell_rate":"34.05","currency":"Saudi Riyal","flagicon":"SA","countrycode":"SAR"},{"buy_rate":"93.75","sell_rate":"94.70","currency":"Australian Dollar","flagicon":"AU","countrycode":"AUD"},{"buy_rate":"34.50","sell_rate":"34.85","currency":"U.A.E Dirham","flagicon":"AE","countrycode":"AED"},{"buy_rate":"96.00","sell_rate":"96.95","currency":"Canadian Dollar","flagicon":"ca","countrycode":"CAD"},{"buy_rate":"129.50","sell_rate":"130.80","currency":"US Dollar","flagicon":"us","countrycode":"USD"},{"buy_rate":"148.00","sell_rate":"149.50","currency":"Euro","flagicon":"eu","countrycode":"EUR"},{"buy_rate":"1.00","sell_rate":"1.00","currency":"Pakistani Rupee","flagicon":"pk","countrycode":"PKR"}]}
Code:
<?php
$url = 'list.JSON';
$data = file_get_contents($url);
$output = json_decode($data);
foreach ($output as $outputs): ?>
<tr>
<td><?php echo $outputs->buy_rate; ?></td>
<td><?php echo $outputs->sell_rate; ?><td>
<td><?php echo $outputs->currency; ?><td>
<td><?php echo $outputs->flagicon; ?></td>
<td><?php echo $outputs->countrycode; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
You just have to get the contents via file_get_contents (by example) and use
json_decode
Here is an example:
//this url is random
$content = file_get_contents('http://myjsondata.com');
//Decode json output to object
$output = json_decode($content);
//parse your object like you want
//I assume that my json contain a key 'data' HERE !
foreach($output->data as $data) {
//Do what you want here
}
Hope this helps

How to rename the $v name?

Here is my code ,output and doubt ....
<?php
$csvData = file_get_contents("http://feed2.abc.com/PriceWs/PriceSnap.asmx/PriceUpdate?item=GC-APR16,SI-MAY16,PA-JUN16,PL-APR16,CL-APR16,BRCL-MAY16,NG-APR16,HO-APR16,HG-MAY16,CC-MAY16,KC-MAY16,CN-MAY16,CT-MAY16,WH-MAY16,SB-MAY16,SY-MAY16,BO-MAY16,&col=last,bid,ask,high,low");
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
foreach($array as $k=>$v){
?>
<table border="1">
<tr>
<td> <?php echo $v[0]; ?><td>
<td> <?php echo $v[1]; ?><td>
<td> <?php echo $v[2]; ?><td>
</tr>`enter code here`
<?php
}
?>
OUTPUT WILL BE LIKE THIS:
GC-APR16 1234.40 1233.30
SI-MAY16 15.180 15.180
PA-JUN16 538.10 539.10
PL-APR16 954.50 955.60
HG-MAY16 2.0750 2.0745
CC-MAY16 2851.0 2849.0
KC-MAY16 119.90 119.90
CN-MAY16 361.75 361.50
CT-MAY16 59.44 59.42
WH-MAY16 460.25 460.00
SB-MAY16 14.33 14.33
SY-MAY16 905.00 905.00
BO-MAY16 33.87 33.86
HERE IS MY DOUBT:
INSTEAD OF GC-APR16 need to display "GOLD", SI-MAY16 need to display "SILVER"
PLEASE HELP....
MANY THANKS
$v[0] = GC-APR16 1234.40 1233.30';
// get first two chars
$two_chars = substr($v[0]);
// "multi if-else"
switch($two_chars) {
case 'GC': $new_tx = 'GOLD'; break;
...
default: ; //show error
}
echo $new_tx;

php - display csv data in tabular format

I am new to PHP and I am trying to display the CSV data in my web page with pagination option.This is the code I have so far.
<?php
$names = file('demo.csv');
$page = $_GET['page'];
//constructor takes three parameters
//1. array to be paged
//2. number of results per page (optional parameter. Default is 10)
//3. the current page (optional parameter. Default is 1)
$pagedResults = new Paginated($names, 20, $page);
echo "<ul>";
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
$row1 = str_replace( ',', "\t", $row );
echo "<li>{$row1}</li>";
}
echo "</ul>";
//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
?>
I was having issues with commas getting displayed in my output. However, I have resolved using the str_replace function. Now, I wish to show the data elegantly in a tabular format. I tried the below code that I saw in another link.
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
<table>
<tr>
$row1 = str_replace( ',', "\t", $row );
<td><?php echo "<li>{$row1}</li>";?></td>
</tr>
</table>
}
echo "</ul>";
However, I am not getting output in my screen. Can someone please guide me in the right direction?
<?php
$names = file('demo.csv');
$page = $_GET['page'];
//constructor takes three parameters
//1. array to be paged
//2. number of results per page (optional parameter. Default is 10)
//3. the current page (optional parameter. Default is 1)
$pagedResults = new Paginated($names, 20, $page);
echo "<table border=\"1\">";
//use the following line to manually display column names,
//if they're not in the 1st row of the CSV file
echo "<tr><td>Column 1 name</td><td>Column 2 name</td><td>Column 3 name</td></tr>";
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
echo "<tr><td>";
$row1 = str_replace( ',', "</td><td>", $row );
echo $row1;
echo "</td></tr>";
}
echo "</table>";
//important to set the strategy to be used before a call to fetchPagedNavigation
$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
?>
You are mixing HTML and PHP a little to loosely. Fix like this:
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
echo "<table>";
echo "<tr>";
$row1 = str_replace( ',', "\t", $row );
echo "<td>";
echo "<li>{$row1}</li>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
echo "</ul>";
or like this:
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
?>
<table>
<tr>
<?php $row1 = str_replace( ',', "\t", $row ); ?>
<td><?php echo "<li>{$row1}</li>";?></td>
</tr>
</table><?php
}
echo "</ul>";
The first one obviously having the preference, as it as much more readable.
Your tables are not placed correctly in the loop.
Please refer the following code:
<table><?php
while($row = $pagedResults->fetchPagedRow()) {
//when $row is false loop terminates
?>
<tr>
<?php
$row1 = str_replace( ',', "\t", $row );
?>
<td><?php echo $row1;?></td>
</tr>
<?php
}
?></table>

Wordpress plugin display query in linked file

I am creating a wordpress plugin that will query a db based off of user entered parameters and display the results in a linked html file. I can get it to display the html page, but the results variable is not passing through.
Here is how I am displaying the linked HTML file:
//This is set in another location but
$template = 'results';
//Execute SQL
global $wpdb;
$result = $wpdb->get_results($sql);
//Load template
$content = file_get_contents( plugins_url( 'template-files/'.$template.'.php',__FILE__ ) );
foreach ( $result as $r ){
$contentCopy = $content;
echo jww_display_php_file($contentCopy, $r);
}
function jww_display_php_file( $content, $r ){
$arr = (array)$r;
ob_start() && extract($arr, EXTR_SKIP);
eval('?>'.$content);
$content = ob_get_clean();
ob_flush();
$content .= "<hr>";
return $content;
}
Here is what I have in the HTML File:
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td>Name</td>
<td><?php echo $Name; ?></td>
</tr>
</table>
Thanks in advance for any help
First of all, your results.html should be results.php, you just can't use php variables or functions inside an HTML file, so rename your file to results.php and then try this
$result = $wpdb->get_results($sql);
$content = file_get_contents( plugins_url( 'template-files/results.php',__FILE__ ) );
foreach ( $result as $r ){
$contentCopy = $content;
echo jww_display_file($contentCopy, $r);
}
function jww_display_file( $content, $r ){
$arr = (array)$r;
ob_start() && extract($arr, EXTR_SKIP);
eval('?>'.$content);
$content = ob_get_clean();
ob_flush();
$content .= "<hr>";
return $content;
}
Finally, inside your results.php file, change following
<td><?php echo $r->Name; ?></td>
<td><?php echo $r->Age; ?></td>
<td><?php echo $r->DOB; ?></td>
to
<td><?php echo $Name; ?></td>
<td><?php echo $Age; ?></td>
<td><?php echo $DOB; ?></td>
Note : eval is evil but it's not a problem when you are using an internal file from your server and you know the code is secure, this way, framework like Laravel loads a view file and mix variables from controller in their MVC framework.
I renamed my results.php to results.html, changed the $content = file_get_contents( plugins_url( 'template-files/'.$template.'.html',FILE ) ); and it works perfectly!

Categories