Wordpress plugin display query in linked file - php

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!

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:

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

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>

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>

Loop separated text into variables

Im using this PHP to display the contents or text files held in a directory, the text files all follow the same format.
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
There are 7 $items in each text file:
tag,name,description,text1,text2,text3,date
So instead of outputting $item, can i give each its own variable?
Thanks.
Try this:
$contents = file_get_contents($filename);
list($tag, $name, $description, $text1, $text2, $text3, $date) = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
echo "<tr><td>$tag</td></tr>\n";
echo "<tr><td>$name</td></tr>\n";
echo "<tr><td>$description</td></tr>\n";
echo "<tr><td>$text1</td></tr>\n";
echo "<tr><td>$text2</td></tr>\n";
echo "<tr><td>$text3</td></tr>\n";
echo "<tr><td>$date</td></tr>\n";
echo '</table>';
Try:
while(list($tag,$name,$desc,$text1,$text2,$text3,$date) = each($items){
// do something
}
Treat the text file as a csv file seperated by the ¬ char.
http://www.php.net/manual/en/function.fgetcsv.php
Then you can either rely upon a header file to describe the fields ( columns ) or access them numerically.

Categories