Echoing HTML correctly from PHP - php

I have a class with a method called paint() so i call $object->paint(); and it returns the html code to display the object the way i like it.
In a function, i have an array of those objects, so i do something like this:
$code = '<p class="wrapper">';
foreach( $object_arr as $object ){
$code .= $object->paint();
}
$code .='</p>';
echo $code;
but the result iḿ getting is this:
<p class="wrapper"></p>
<figure id="f1">Figure 1</figure>
<figure id="f2">Figure 2</figure>
...
<figure id="fn">Figure n</figure>
The function paint() returns the code to paint the object, i was expecting to see:
<p class="wrapper">
<figure id="f1">Figure 1</figure>
<figure id="f2">Figure 2</figure>
...
<figure id="fn">Figure n</figure>
</p>
What am i doing it wrong?

The result you're looking at might be corrected by your browser. p does not accept figure as a child, so the browser might correct it by closing your first <p class="wrapper">.

Some more code would be helpful, but this might put you on the right track.
What is $object_arr an array of. Can you post the example of the object in the object array?
With my example you would have to pass in the index as well to get the id="fnn".
If you post some more code I can clarify my answer.
<?php
function paint($str){
return '<figure id="fn">'.$str.'</figure>';
}
$object_arr =Array('happy','beans');
$code = '<p class="wrapper">';
foreach( $object_arr as $object ){
$code .= paint($object);
}
$code .='</p>';
echo $code;

If you're using single quotes, then put a tab before the method call:
$code .= ' ' . $object->paint();
But this would be easier:
$code .= "\t" . $object->paint();

Related

why is this php code not working?

This is the code I am using to scrape specific data from http://www.partyhousedecorations.com
however I keep getting this error (Fatal error: Call to a member function children() on a non-object in C:\wamp\www\webScraping\PartyHouseDecorations.php on line 8 )and I am stuck and can't seem to be able to fix it.
This is my code:
<?php
include_once("simple_html_dom.php");
$serv=$_GET['search'];
$url = 'http://www.partyhousedecorations.com/category-adult-birthday-party-themes'.$serv;
$output = file_get_html($url);
$arrOfStuff = $output->find('div[class=product-grid]', 0)->children();
foreach( $arrOfStuff as $item )
{
echo "Party House Decorations".'<br>';
echo $item->find('div[class=name]', 0)->find('a', 0)->innertext.'<br>';
echo '<img src="http://www.partyhousedecorations.com'.$item->find('div[class=image]', 0)->find('img', 0)->src.'"><br>';
echo str_replace('KWD', 'AED', $item->find('div[class=price]',0)->innertext.'<br>');
}
?>
Looks like $output->find('div[class=product-grid]', 0) doesn't return an object with a method called children(). Maybe it's returning null or something that's not an object. Put it in a separate variable and look what the value of that variable is.
$what_is_this = $output->find('div[class=product-grid]', 0);
var_dump($what_is_this)
Update:
I debugged your program, and apart from the simple html dom parser seemingly expecting classes to be given as 'div.product-grid' instead of 'div[class=x]' it also turns out that the webpage responds by returning a product list instead of a product grid. I've included a working copy below.
<?php
include_once("simple_html_dom.php");
$serv=$_GET['search'];
$url = 'http://www.partyhousedecorations.com/category-adult-birthday-party-themes';
$output = file_get_html($url);
$arrOfStuff = $output->find('div.product-list', 0)->children();
foreach( $arrOfStuff as $item )
{
echo "Party House Decorations".'<br>';
echo $item->find('div.name', 0)->find('a', 0)->innertext.'<br>';
echo '<img src="http://www.partyhousedecorations.com'.$item->find('div.image', 0)->find('img', 0)->src.'"><br>';
echo str_replace('KWD', 'AED', $item->find('div.price',0)->innertext.'<br>');
}
?>

Using php function as a link which is in an echoed function

i am trying to insert a link in an echoed line,
regular links work, but not this one, cant figure it out what's wrong
if($gallery_images != ''){
foreach ($gallery_images as $gallery_image){
$thumb = wp_get_attachment_image_src($gallery_image[SN.'gallery_post_image']['id'], 'post-thumb', false);
echo '<li><a <img src="'.$thumb[0].'" alt="'.$gallery_image[SN.'gallery_post_title'].'" /><p class="flex-caption">'.$gallery_image[SN.'gallery_post_title'].'</p></li>';
}
}
the_permalink() is a not a return function, it echoes the permalink. Replace it with get_permalink, which returns the permalink.
if($gallery_images != ''){
foreach ($gallery_images as $gallery_image){
$thumb = wp_get_attachment_image_src($gallery_image[SN.'gallery_post_image']['id'], 'post-thumb', false);
echo '<li><a <img src="'.$thumb[0].'" alt="'.$gallery_image[SN.'gallery_post_title'].'" /><p class="flex-caption">'.$gallery_image[SN.'gallery_post_title'].'</p></li>';
}
}
Your first problem is that. You don't include a function on a string that way.
echo '<li><a href="**<?php the_permalink(); ?>**">
Try this:
echo '<li><a href="'.the_permalink().'">
Then
.$gallery_image[SN.'gallery_post_title'].
You got a syntax error there.
SN.'gallery_post_title' // notice SN
It's fine if you define SN though.
Also, why do you have a close curly brace }?
Did you just copy and paste your code here sloppily or is that intentional? It's confusing if it is.

How can I keep an HTML snippet in a separate file, plug variables in as needed, and echo it out on demand?

For instance, let's say I have a snippet of code, which I'd like to keep separate. for now, we'll call it snippet.php.
snippet.php would be a simple block of reusable HTML which would have php variables in it. Something like this:
<article>
<h1>{$headline}</h1>
<p>${$body}</p>
</article>
I'd like to be able to return this code from a function, along the lines of this:
function writeArticle($headline, $body){
return "contents of snippet.php using the variables passed in to the function"
}
I know I could just use html in a string to return, but the actual snippet would be fairly complex, and I want it to be modular.
One method is using file_get_contents and str_replace
HTML:
<article>
<h1>[-HEADLINE-]</h1>
<p>[-BODY-]</p>
</article>
PHP:
function writeArticle($headline,$body){
$content = file_get_contents("[add your html directory here]/file.html",true);
$content = str_replace("[-HEADLINE-]",$headline,$content);
$content = str_replace("[-BODY-]",$body,$content);
echo $content;
}
You can use output buffering and include the file so the PHP variables get evaluated. However, since you are not using <?php PHP tags ?> you will need to wrap it in HEREDOC format (http://php.net/manual/en/language.types.string.php). Scroll down to Heredoc on the page.
snippet.php
$output = <<<HEREDOC
<article>
<h1>{$headline}</h1>
<p>{$body}</p>
</article>
HEREDOC;
function writeArticle($headline, $body){
ob_start();
include('snippet.php');
$snippet = ob_get_clean();
return $snippet
}
You could do this:
HTML DOCUMENT
Include('blockClass.php');
$block = new blockClass();
echo $bl = $block->block($headline, $body);
CLASS DOCUMENT
class blockClass{
function block($headline, $body){
$var ='<article>
<h1>' . $headline . '</h1>
<p>' . $body . '</p>
</article>';
return $var;
}
}
I had the same question and ended up solving it like this. I feel like this is the cleanest approach. Just turn php on and off within the function.
<?php
function writeArticle($headline, $body){
?>
<article>
<h1><?php echo $headline; ?></h1>
<p><?php echo $body; ?></p>
</article>
<?php
}
?>
writeArticle('foo', 'bar');

How do I catch the HTML generated by a function?

I have a php function that generates HTML code like below
function j_uf_SomeFunction($some_var) {
?><div class="db_photo">
<img alt="<?php echo some_php_function ?>" src="<?php echo $some_var; ?>" />
</div><?php
}
Of course, its much more advanced and add all sorts of user options.
In most case I place this function inline, as opposed to have to append it to a string. However, I've come to the first occurrence (probably not the last occurrence) where I need to store the rendered HTML in a string and not have it sent straight off to the parser for building the page.
I need to cut the function off and tell it to take the html generated and store it in a string, and not send it off to the page, only on certain situations.
function j_uf_SomeFunction($some_var) {
ob_start();
?><div class="db_photo">
<img alt="<?php echo some_php_function ?>" src="<?php echo $some_var; ?>" />
</div><?php
return ob_get_clean();//suggestion by GWW
}
ob_start() is starting buffer receive
ob_get_clean() cleans current buffer and returns its value.
More info on http://php.net/manual/en/function.ob-start.php
ob * output buffering
It sounds like output buffers are one possible solution to your problem.
You use an output buffer like so:
ob_start();
j_uf_SomeFunction($someVar);
$buffer = ob_get_contents();
ob_end_clean();
The $buffer variable now contains anything printed out by the function.
It's important to always close output buffers with ob_end_clean or ob_end_flush. You can read more here: http://php.net/manual/en/book.outcontrol.php
Regards,
Chris
I don't I have a template system to parse this functions value into... its not your standard function call.
sure you do... its jsut contained within the function :-)
using translation:
function j_uf_SomeFunction($some_var) {
$html = "<div class="db_photo"><img alt="%some_function_result%" src="%some_var%" /></div>";
$tokens = array(
'%some_var%' => $some_var,
'%some_function_call_result%' => some_function_call()
);
return strtr($html, $tokens); // or echo
}
using string manipulation:
function j_uf_SomeFunction($some_var) {
$html = '<div class="db_photo"><img alt="%s" src="%s" /></div>';
return sprintf($html, some_function_call(), $some_var); //or echo
}
if some_function_call actually outputs html directly with its own echo then jsut use a buffer:
function j_uf_SomeFunction($some_var) {
ob_start();
some_function_call();
$somefunc = ob_get_clean();
$html = '<div class="db_photo"><img alt="%s" src="%s" /></div>';
return sprintf($html, $somefunc, $some_var); //or echo
}

PHP function return. Cheats allowed

OK.
I have a very long and pretty complicated function.
It looks almost like this one:
<?php
function hello() {
echo 'My Function!' ?>
<ul>
<li> Blablabla </li>
<ul>
(...)
<?php } ?>
The HUGE problem here is that I'm UNABLE to echo anything.
My function HAVE to return it's contents instead of echoing or direct outputting (it has to be that way, it's a Wordpress shortcode and when I echo - the contents are getting displayed at the top of the page - ALWAYS, not in the place where I want them):
<?php
function hello() {
$output .= 'My Function!';
$output .= '<ul>';
$output .='<li> Blablabla </li>';
$output .='<ul>';
(...)
return $output;
} ?>
I hope it's easy till now.
Now, the real problems are:
I have tons of direct input code like:
?>
<div>
<span>
<p>Smth</p>
<a>smth</a>
</span>
</div>
<?php
Adding $output everywhere kills the nice paragraphs/whitespace and code is getting VERY HARD to read and understand (and all HTML elements are parts of variable now, so even my php editor is not treating them well and coloring them as PHP elements).
And another thing, I have tons of lines like this one:
<a href="<?php bloginfo('template_directory'); ?>/includes/php/timthumb.php?src=<?php echo $url; ?>&h=<?php if($items=="one") echo 320; elseif($items=="two") echo 230; elseif($items=="three") echo 180; elseif($items=="four") echo 130; ?>&w=<?php if($items=="one") echo 600; elseif($items=="two") echo 420; elseif($items=="three") echo 277; elseif($items=="four") echo 203; ?>" title="<?php the_title(); ?>" class="link">
(yes, this is a single line)
And I have absolutely no idea how to add such lines to $output.
$output .= '<a href="<?php bloginfo('template_directory'); ?>/includes/php/timthumb.php?src=<?php echo $url; ?>&h=<?php if($items=="one") echo 320; elseif($items=="two") echo 230; elseif($items=="three") echo 180; elseif($items=="four") echo 130; ?>&w=<?php if($items=="one") echo 600; elseif($items=="two") echo 420; elseif($items=="three") echo 277; elseif($items=="four") echo 203; ?>" title="<?php the_title(); ?>" class="link"> ';
Doesn't work of course (even with \'s before ' and ").
I believe there MUST be an easier way to attach all the code to return, but how?
I've tried with ob_start(); before code and return ob_get_clean(); after, but it outputs shortcode name instead of contents.
Its very hard to imagine what the problem you are trying to solve here is - although I'm not familiar with wordpress. Can't you just call the function where the output is supposed to go?
You could use output buffering - use echo/print as usual but...
ob_start();
hello();
$output=ob_get_contents();
ob_end_clean();
But that doesn't solve the problem that you still need to send to the browser at the right place in the page - and if you can do:
print $output;
in the right place, then you can surely do:
hello();
in the same place.
I agree with symcbean, but this might be a more practical approach at integrating with Wordpress: if you now have a single function called hello( ) which displays HTML, you might want to consider renaming that function to hello_content( ) (or something similar) and replace the hello( ) function with the suggestion symcbean gave you:
function hello_content( ) {
echo "foo";
}
function hello( ) {
ob_start( );
hello_content( );
return ob_get_clean( );
}
That should fix your immediate issue.
PHP Heredoc syntax will keep things looking neat and tidy and you can return the output to a variable. As long as you don't require any constants it will work fine.
You use it in this fashion:
function bar() {
$var = <<<EOV
anything here
anything there
EOV;
return $var;
}

Categories