Fetching JSON data from a url through PHP - 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

Related

Displaying xml soap response to html table using PHP

I'm trying to display the xml soap response to HTMl table using PHP but I'm getting warning and data are not showing. Here is what I tried. Do you have any Idea what is wrong in my code? I'm new to XML. Thank you in advance.
XML Response:
Array ( [soap_Body] => Array ( [RunVRSCommandResult] => STOREREPORTFILE
MANGO00011005050APPLE00021006040MELON00031007030WATERMELON00041008020
CODE:
<body>
<table border="0" cellpadding="2" cellspacing="3" width="100%">
<tr>
<th>Fruits Name</th>
<th>Quantity</th>
<th>Sold</th>
<th>Remaining</th>
</tr>
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
XML
));
$response = curl_exec($curl);
curl_close($curl);
$plainXML = mungXML(trim($response));
$arrayResult = json_decode(json_encode(SimpleXML_Load_String($plainXML,
'SimpleXMLElement', LIBXML_NOCDATA)), true);
foreach ($arrayResult as $data) {
?>
<tr>
<td><?php echo $data->fruit_name; ?></td>
<td><?php echo $data->quantity; ?></td>
<td><?php echo $data->sold; ?></td>
<td><?php echo $data->remaining; ?></td>
</tr>`enter code here`
<?php
}
function mungXML($xml)
{
$obj = SimpleXML_Load_String($xml);
if ($obj === FALSE) return $xml;
$nss = $obj->getNamespaces(TRUE);
if (empty($nss)) return $xml;
$nsm = array_keys($nss);
foreach ($nsm as $key) {
$rgx
= '#'
. '('
. '\<'
. '/?'
. preg_quote($key)
. ')'
. '('
. ':{1}'
. ')'
. '#';
$rep
= '$1'
. '_';
$xml = preg_replace($rgx, $rep, $xml);
}
return $xml;
}
?>
OUTPUT:

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

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

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!

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>

Categories