I'm new to PHP and I come from Objective-C. I need to create a plugin for WP that returns an HTML table where each row is populated by data from JSON. In essence, as an example, I need to replace echo with return:
$jsonurl = "http://xxxx/club/api/xxxx/category/";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
//print_r ($json_output);
echo "<table>";
foreach ( $json_output->result as $result )
{
echo "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
echo "</table>" ;
That works! I can see output as expected. But for showing table in WP through Shortcode, I need return and no echo. So how can I replace the echo with return?
I tried:
function foobar_func(){
$html= "<table>";
foreach ( $json_output->result as $result )
{
$html. = "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
$html. = "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );
without success. Any help is welcome.
UPDATE: Same result (no work). I will exit crazy.
function foobar_func($json_output){
$html= "<table>";
foreach ( $json_output->result as $result )
{
$html. = "<tr><td>".$result->id."</td><td>".$result->categoryKond."</td> <td>".$result->ranking."</td>";
}
$html. = "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );
please try ob_start() method i think it useful to you.
http://php.net/manual/en/function.ob-start.php
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
Variable scope is your problem here. $json_output isn't accessible within the function.
Change to the following:
function foobar_func(){
global $json_output;
$html= "<table>";
Alternatively to calling it as a global variable, you can pass it within the function call.
function foobar_func($json_output){
And then when you call the function, use foobar_func($json_output)
After investigating I found the way out. But honestly I can't understand why this code works. Thank you all for putting me on the right path.
Code:
function foobar_func($json_output){
$jsonurl = "http://xxxx/club/api/xxx/category/";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
echo "<table>";
foreach ( $json_output->result as $result )
{
echo "<tr><td>".$result->id."</td><td>".$result->categoryKind."</td><td>".$result->ranking."</td>";
}
echo "</table>" ;
return $html;
}
add_shortcode( 'foobar', 'foobar_func' );
Related
how can I output this array into html table?
for each row I would like to output it like this, within the foreach;
echo "<td>".$lat."</td><td>".$long."</td>";
as per example on https://developer.here.com/documentation/routing-waypoints/topics/quick-start-simple-car.html
I have tried the code
$api_url = "https://wse.api.here.com/2/findsequence.json?start=Berlin-Main-Station;52.52282,13.37011&destination1=East-Side-Gallery;52.50341,13.44429&destination2=Olympiastadion;52.51293,13.24021&end=HERE-Berlin-Campus;52.53066,13.38511&mode=fastest;car&app_id=ID&app_code=CODE";
$api_response = file_get_contents($api_url);
$api_response_decoded = json_decode($api_response, true);
foreach($api_response_decoded as $api_response_decoded_row){
print_r($api_response_decoded_row[0][waypoints]);
}
and also tried
print_r($api_response_decoded_row[0][waypoints][id]);
and also tried
echo($api_response_decoded_row[0][waypoints][id]);
and also tried
implode($api_response_decoded_row[0][waypoints][id]);
Here's one way you could do it if the comments didn't already help you enough.
foreach($api_response_decoded as $api_response_decoded_rows){
foreach ($api_response_decoded_rows[0]['waypoints'] as $waypoint) {
$html = '
<td>'.$waypoint['lat'].'</td>
<td>'.$waypoint['lng'].'</td>
';
echo $html;
}
}
Thanks to commenters and answerers. In case it helps someone else, full working code is therefore;
$api_url = "https://wse.api.here.com/2/findsequence.json?start=Berlin-Main-Station;52.52282,13.37011&destination1=East-Side-Gallery;52.50341,13.44429&destination2=Olympiastadion;52.51293,13.24021&end=HERE-Berlin-Campus;52.53066,13.38511&mode=fastest;car&app_id=ID&app_code=CODE";
$api_response = file_get_contents($api_url);
$api_response_decoded = json_decode($api_response, true);
echo "<table>";
foreach($api_response_decoded as $api_response_decoded_rows){
foreach ($api_response_decoded_rows[0]['waypoints'] as $waypoint) {
$html = '<tr><td>'.$waypoint['sequence'].'</td><td>'.$waypoint['id'].'</td><td>'.$waypoint['lat'].'</td><td>'.$waypoint['lng'].'</td></tr>';
echo $html;
}
}
echo "</table>";
I am using Simple HTML Dom, trying to get strings from a website. When I print out $title[0] within the function it shows just one string, but when I safe it in the return array and print out the return value, I receive a never ending text with RECURSION.
I don't understand why it would work with the second variable $oTitle.
<?php
include 'scripts/simple_html_dom.php';
function getDetails($id) {
$url = "http://www.something.com";
$html = file_get_html ( $url );
$title = $html->find('span[itemprop=name]');
print_r($title[0] . PHP_EOL); //prints out the correct title
$oTitle = "Something"; //there is also code for this variable but it works as it should
$details = array("Title" => $title[0], "Original Title" => $oTitle);
return $details;
flush ();
}
$values = getDetails($number);
print_r($values); //code breakes here
?>
Take a look at this page: http://simplehtmldom.sourceforge.net/
As I can see, you're using this parser.
In order to get HTML content you should use something like this:
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
In order to drop content, you should use something like this:
// Dump contents (without tags) from HTML
echo file_get_html('http://www.google.com/')->plaintext;
Try this code:
<?php
include 'simple_html_dom.php';
function getDetails() {
$url = "http://www.godaddy.com";
$html = file_get_html ( $url );
$title = getTitle($url);
echo $title; //prints out the correct title
$oTitle = "Something"; //there is also code for this variable but it works as it should
$details = array("Title" => $title, "Original Title" => $oTitle);
return $details;
flush ();
}
function getTitle($Url){
$str = file_get_contents($Url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
$values = getDetails();
print_r($values); //code breakes here
?>
Edit |
This is a simple url...
The issue is I have to echo it in a while loop.
Which means I cant use php tags.
MY cancatenation sucks... I tried it for hours (noob) Please help
The issue is I have to echo it in a while loop. Which means I cant use php tags.
It doesn't mean that.
<?php
while ($condition) {
?>
Edit |
<?php
}
?>
(But if you have a list of links, then use list markup (ul/ol/li) not | characters).
try something like this
echo 'Edit'
It's pretty simple:
<?php
While(condition){
?>
Edit
<?php
}
?>
I would suggest to "prepare" the whole element in php. Something like this:
foreach ($arr as $key) {
print 'Edit';
}
<?php
while ($condition) {
echo 'Edit';
}
?>
You can also use heredoc syntax.
Sidenote, I would collect them all and echo it out once in the end
$text = '';
while ($foo) {
$text .= 'Edit';
}
echo $text;
// or heredoc
$text = '';
while ($foo) {
$text .= <<<_HTML
Edit
_HTML;
}
echo $text;
// or array
while ($foo) {
$data[] = 'Edit';
}
if(!empty($data)){
echo '<p>'.implode('</p><p>',$data).'</p>';
}
if it is a template file in php then always use this type of syntax
code:
<?php
$i=0;
while($i<10) : ?>
<div><?php echo $i;?></div>
<?php
$i++;
endwhile;?>
I'm stuck on how to write the test.php page result (after php has run) to a string:
testFunctions.php:
<?php
function htmlify($html, $format){
if ($format == "print"){
$html = str_replace("<", "<", $html);
$html = str_replace(">", ">", $html);
$html = str_replace(" ", " ", $html);
$html = nl2br($html);
return $html;
}
};
$input = <<<HTML
<div style="background color:#959595; width:400px;">
<br>
input <b>text</b>
<br>
</div>
HTML;
function content($input, $mode){
if ($mode =="display"){
return $input;
}
else if ($mode =="source"){
return htmlify($input, "print");
};
};
function pagePrint($page){
$a = array(
'file_get_contents' => array($page),
'htmlify' => array($page, "print")
);
foreach($a as $func=>$args){
$x = call_user_func_array($func, $args);
$page .= $x;
}
return $page;
};
$file = "test.php";
?>
test.php:
<?php include "testFunctions.php"; ?>
<br><hr>here is the rendered html:<hr>
<?php $a = content($input, "display"); echo $a; ?>
<br><hr>here is the source code:<hr>
<?php $a = content($input, "source"); echo $a; ?>
<br><hr>here is the source code of the entire page after the php has been executed:<hr>
<div style="margin-left:40px; background-color:#ebebeb;">
<?php $a = pagePrint($file); echo $a; ?>
</div>
I'd like to keep all the php in the testFunctions.php file, so I can place simple function calls into templates for html emails.
Thanks!
You can use output buffering to capture the output of an included file and assign it to variable:
function pagePrint($page, array $args){
extract($args, EXTR_SKIP);
ob_start();
include $page;
$html = ob_get_clean();
return $html;
}
pagePrint("test.php", array("myvar" => "some value");
And with test.php
<h1><?php echo $myvar; ?></h1>
Would output:
<h1>some value</h1>
This may not be exactly what you're looking for but it seems you want to build an engine of sorts for processing email templates into which you can put php functions? You might check out http://phpsavant.com/ which is a simple template engine that will let you put in php functions directly into a template file as well as basic variable assignment.
I'm not sure what printPage is supposed to be doing but I would re-write it like this just to make it more obvious because the array of function calls is a bit complicated and I think this is all that is really happening:
function pagePrint($page) {
$contents = file_get_contents($page);
return $page . htmlify($contents,'print');
};
and you might consider getting rid of htmlify() function and use either of the built-in functions htmlentities() or htmlspecialchars()
Seems like my original method may not have been the best way of going about it. Instead of posing a new question on the same topic, figured it was better to offer an alternate method and see if it leads to the solution I am after.
testFunctions.php:
$content1 = "WHOA!";
$content2 = "HEY!";
$file = "test.html";
$o = file_get_contents('test.html');
$o = ".$o.";
echo $o;
?>
text.php:
<hr>this should say "WHOA!":<hr>
$content1
<br><hr>this should say "HEY!":<hr>
$content2
I'm basically trying to get $o to return a string of the test.php file, but I want the php variables to be parsed. as if it was read like this:
$o = "
<html>$content1</html>
";
or
$o = <<<HTML
<html>$content1</html>
HTML;
Thanks!
I have a slight problem with the echo statement outputting wrongly. Forexample when i do
echo "<div id=\"twitarea\">" . fetchtwitter($rss) . "</div>";
it displays function output but OUTSIDE of twitarea div. What is the cause of this behavior perhaps syntax?
thanks in advance
Here is the actual function
require_once('includes/magpie/rss_fetch.inc');
$rssaldelo = fetch_rss('http://twitter.com/statuses/user_timeline/12341234.rss');
function fetchtwitter($rsskey){
foreach ($rsskey->items as $item) {
$href = $item['link'];
$title = $item['title'];
print "<li class=\"softtwit\">$title</li><br>";
} }
Simply :
<?php
echo "<div id=\"twitarea\">";
fetchtwitter($rss);
echo "</div>";
?>
fetchtwitter($rss) is echoing output (it doesn't return it).
With that you don't have to modify fetchtwitter().
fetchtwitter() probably does an echo() of its own, instead of returning the string. The function is executed while echo prepares the whole string for output, before the string is printed.
Does fetchtwitter(...) write the output directly to the browser instead of returning it? Try something like:
<?php
ob_start();
fetchtwitter($rss);
$twitter = ob_get_clean();
echo "<div id=\"twitarea\">" . $twitter . "</div>";
?>
Or if you can modify the source of fetchtwitter(), get it to concatenate and return the string instead of echoing it.
In case you didn't see my comment.
Try using a return in your fetchtwitter() function rather than the echo that you have in there.
you could try delimiters maybe it helps
$twitter = fetchtwitter($rss);
ob_start();
echo <<<HTML;
<div id="twitarea">$twitter</div>
HTML;
echo ob_get_clean();
update
You can modify your function like this too
require_once('includes/magpie/rss_fetch.inc');
$rssaldelo = fetch_rss('http://twitter.com/statuses/user_timeline/12341234.rss');
function fetchtwitter($rsskey){
$bfr ="";
foreach ($rsskey->items as $item){
$href = $item['link'];
$title = $item['title'];
$bfr .= "<li class=\"softtwit\"> target=\"_blank\">$title</li><br>";
}
return $bfr;
}