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

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

Related

Using Foreach to print the values

Stored JSON decoded data in a variable that variable array of data I need to print that I tried below code but I get a result in that one bug called see below image.
You could try writing
$pack = json_encode($packs,true);
out of echo, just below
$packs=data['packs'];
$no = 1;
while($data = mysqli_fetch_array($findCustomer,MYSQLI_ASSOC)){
echo '
<tr>
<td>'.$no.'</td>
<td>'.$data['NAME'].'</td>
<td>'.$data['PHONE'].'</td>
<td>'.$data['STB_NUMBER'].'</td>
<td>'.$data['VC_NUMBER'].'</td>
<td>'.$data['agent_name'].'</td>
<td>'.$data['created_on'].'</td>';
echo '<td>';
$array =$data['packs'];
$pack = json_decode($array,true);
foreach ($pack as $value) {
echo 'Pack-Name:'.$value['pack_dsc']."<br>Pack-Amount:".$value['pack_base_prc']."<br>";
}
echo '</td>
</tr>';
$no++;
}

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

Array an array one minute and not the next? Invalid argument supplied for foreach()

For some reason my code is an array one minute and not the next. I'm just learning php and I can't figure this out. I've used this page to figure most of this out: How to add two Google charts on the one page?
My code is also used on a page that shows the data as a table. On that page it works fine....but for some reason I'm getting Invalid argument supplied for foreach() on the pie charts page...and it's saying it's not an array. I'm not sure how to go about fixing this.
The url I'm using is ?action=scores&data=pie so it should list all of the universities in "get_universities()" (there's 3 there).
Can anyone help please?
The switch:
// Showing scores
case 'scores':
// Grab the Uni ID and use the appropriate query
if (isset($_GET['uni_id']))
{
$uni_id = $_GET['uni_id'];
$uni = get_university($uni_id);
}
else
{
$uni = get_universities();
}
// We have to display this data according to the request
if (isset($_GET['data']))
{
$data = $_GET['data'];
}
else
{
$data = "table";
}
// Display the data accordingly
include (root . '/view/' . $data . '_view.php');
break;
The pie graphs:
// Create the data table.
<?php foreach ($uni as $uni) : ?>
var data<?php echo $uni['university_id']; ?> = new google.visualization.DataTable();
data<?php echo $uni['university_id']; ?>.addColumn('string', 'Area');
data<?php echo $uni['university_id']; ?>.addColumn('number', 'Score');
data<?php echo $uni['university_id']; ?>.addRows([
['Teaching', <?php echo $uni['teaching_score']; ?>],
['Intl Outlook', <?php echo $uni['int_outlook_score']; ?>],
['Industry Income', <?php echo $uni['ind_income_score']; ?>],
['Research', <?php echo $uni['research_score']; ?>],
['Citations', <?php echo $uni['citations_score']; ?>]
]);
<?php endforeach ?>
// Set chart options
<?php foreach ($uni as $uni) : ?>
var options<?php echo $uni['university_id']; ?> = {'title':'<?php echo $uni['university_name']; ?> Scores',
'width':400,
'height':300};
<?php endforeach ?>
// Instantiate and draw our chart, passing in some options.
<?php foreach ($uni as $uni) : ?>
var chart<?php echo $uni['university_id']; ?> = new google.visualization.PieChart(document.getElementById('chart_div<?php echo $uni['university_id']; ?>'));
chart.draw(data<?php echo $uni['university_id']; ?>, options<?php echo $uni['university_id']; ?>);
<?php endforeach ?>
The table view (which works):
<?php foreach ($uni as $uni) : ?>
<td>
<a href="?uni=<?php echo $uni['university_id']; ?>">
<?php echo $uni['university_name']; ?>
</a>
</td>
<etc>
The problem is with your foreach statement:
foreach ($uni as $uni) :
Here you override the $uni variable. Use different names for the collection and item, eg:
foreach ($uni as $theUni) :
// also change instances of $uni below
EDIT
The above is wrong. The parsing of the first parameter of foreach happens only once so in that foreach it won't be a problem. However a foreach is not a new scope, so if you plan to reuse the array variable, you need to choose a different name as the iterator so it won't get overridden.
$a = array(); // $a is array
foreach ($a as $a) {
// $a is element of original $a
}
// $a is the last element of the original $a array
foreach ($a as $a) // Fail, since $a is not an array anymore

Undefined offset issue in explode

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>

How to display a php 3 level array in table form

Currently I have a PHP 3 level array. How do I display it in a table form? Using print_r I could display out the full array but I need to beautify it to show in a table form. Is it possible?
Sample of the array to be inserted is as shown in another posting: PHP foreach with Nested Array?
So... each level of the array should be an embedded table?
<table>
<?php // FIRST LEVEL
foreach ($myArray as $first_level): ?>
<tr>
<td>The header of the first level, here's some data <?php echo $first_level['some_data']; ?></td>
</tr>
<tr>
<td>
<table>
<?php // SECOND LEVEL
foreach($first_level['second_level'] as $second_level): ?>
<tr>
<td><?php echo $second_level['some_data']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</td>
</tr>
<?php endforeach; ?>
</table>
..and keep repeating the pattern
So many ways to do it, even more so since you didn't provide a template for the output format ....
Let's assume each element $e of the input array $src stands for one row in the table.
Then $e[0] is the string element (one, two, three) and $e[1] is the corresponding array 1,2,3, 4,5,6 or 7,8,9.
Let's put $e[0] into <th>...</th> elements.
foreach( $src as $e ) {
echo '<th>', $e[0], '</th>';
}
and then wrap each element in $e[1] in <td>....</td>.
foreach( $src as $e ) {
echo '<th>', $e[0], '</th>';
foreach($e[1] as $v) {
echo '<td>', $v, '</td>';
}
}
now wrap that into another <tr>...</tr> and you are done
foreach( $src as $e ) {
echo '<tr>';
echo '<th>', $e[0], '</th>';
foreach($e[1] as $v) {
echo '<td>', $v, '</td>';
}
echo "</tr>\r\n";
}
the same thing a bit shorter (see http://docs.php.net/join)
<?php
$src = getData();
foreach( $src as $e ) {
echo '<tr><th>', $e[0], '</th><td>', join('</td><td>', $e[1]), "</td></tr>\n";
}
function getData() {
return array(
array( 'one', array(1,2,3) ),
array( 'two', array(4,5,6) ),
array( 'three', array(7,8,9) )
);
}
the output is
<tr><th>one</th><td>1</td><td>2</td><td>3</td></tr>
<tr><th>two</th><td>4</td><td>5</td><td>6</td></tr>
<tr><th>three</th><td>7</td><td>8</td><td>9</td></tr>
see also: http://docs.php.net/htmlspecialchars

Categories