March 5, 2012

Problems transferring variables into ob

Question by rix

I use the following code to read a template into the buffer (ob). $vars contains all the variables i want to have access to in the template.

print_r($this->vals);  //prints out an array of values, value1 => '', value2 => ''...
ob_start();
include myTemplate.php
$content = ob_get_contents();
ob_end_clean();
echo $content;

But then in my template $vals is undefined or i don’t have access to it.

Any idea where I’m going wrong?

Thanks,

Answer by Starx

May be a simple typo error. But you are using $vals instead of $vars.

And if this is not the problem put ob_start() at top.

ob_start();
print_r($this->vals);  //prints out an array of values, value1 => '', value2 => ''...
include "myTemplate.php"; //few errors were here, no quotes and semicolon
$content = ob_get_contents();
ob_end_clean();
echo $content;

Just did a quick test, it works.


Update

In case you are trying to get the value of print_r($this -> vals) to $content. There is a very easy way to do this. print_r()[docs] function take another argument as well whether to return or not.

If so, your entire code comes down to this

$content = print_r($this->vals, true); 

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!