I want call a php custom function(writeMsg()) inside a <div> tag.
Below is a code sample of how to do it, but I'm not too sure if this adheres to the syntax of the language?
<?php
function writeMsg() {
echo "This is a test!";
}
echo "<div class='wrapper'>";
for( $i=0; $i < 6; $i++ ) echo "<div>$i **call writeMsg()**</div>";
echo "</div>";
?>
PHP is not recursively embeddable/executable. You cannot embed PHP code inside a PHP string and expect PHP to execute it. Just do:
echo "<div>" . writeMsg() . "</div>"
But note that your function is doing echo, which means it performs IMMEDIATELY output, and the above code sample will effectively execute as
writeMsg();
echo "<div></div>';
Your function should RETURN the string, not echo it.
First change your function to:
function writeMsg() {
return "This is a test!";
}
And then just change your echo to:
echo "<div>" . $i . " " . writeMsg(). "</div>";
Related
Normally i use this code and it's will be echo work good.
<?PHP
echo $row->test_column_1;
?>
But when i tyied to use this code, it's not echo any data. How can i do ?
<?PHP
$i = "1";
echo ${'row->test_column_' . $i};
?>
You can access a dynamic property name like this:
<?php
$i = "1";
echo $row->{'test_column_' . $i};
I am trying to program a Flat File PHP Dictionary (English -> Spanish).
I've got this up to now:
<?php
$data =
'car;coche
cat;gato
fat;gordo
far;lejos';
if($data) {
$line = explode("\n", $data);
for($i = 0; $i<count($line); $i++) {
$item = explode(";", $line[$i]);
if($_GET['word'] == $item[0]) { echo"<div>" . $item[0] . "</div> <div>" . $item[1] . "</div>"; }
else {echo MAIN PAGE;}
}
}
?>
It is perfect because it opens a loop of pages in one php file:
e.g. http://localhost/?word=fat prints "Fat Gordo"
My problem is when creating the main page http://localhost. I tried with else{ echo "MAIN PAGE";} but, wherever I place it, it prints "MAIN PAGEMAIN PAGEMAIN PAGE".
Any help?
that's because you are looping through every line in $data. Whatever the outcome of the if expression is, after that it just goes on to the next iteration and runs the if statement again.
So if you add the } else { echo "mainpage" to your if, it will echo mainpage everytime when $_GET['word'] doesn't match $item[0] (which obviously at every line if $_GET['word'] is not defined)
To avoid this you can add something like this:
if($data && !empty($_GET['word'])) {
(...)
} else {
echo "mainpage";
}
If you have a big dictionary it's also good to break you loop once you have found a matching word:
if($_GET['word'] == $item[0]) {
echo "<div>" . $item[0] . "</div> <div>" . $item[1] . "</div>";
break;
}
Just learning bits in PHP and trying to get simple function for my nav running
function navigation($pages) {
$pages = array($pages);
if($pages) {
echo "<ul class=nav>";
foreach($pages as $id => $page) {
echo "<li><a href=\"page.php?id={$id}\">";
echo strtoupper($page) . "</a>";
}
echo "</ul>";
}
}
Although this function is only returning the first value
navigation("Home", "About us", "Contact us");
Is it possible to put the function values to variable? I'm not sure what I'm doing here wrong.
Remove this:
$pages = array($pages);
And instead call the function like this:
navigation( array("Home", "About us", "Contact us") );
Please note that you should not output HTML like this:
echo "";
But instead make sure that the CSS classname is wrapped in quotes. To achieve this, you could use escaped double-quotes:
echo "";
Or, which would be my personal preference, single quotes in the outer string and normal double quotes inside:
echo '';
Generally you can use single-quotes to define any string in PHP, with only one exception, which is when you want to put special characters in your string, such as:
\n
\r
\t
and so on. These might not be interpreted correctly in a single-quoted string.
Here is a more refined version of your navigation() function:
function navigation(array $pages) {
if(!$pages)
return;
echo '<ul class="nav">';
foreach ($pages as $id => $page) {
echo '<li><a href="page.php?id=' . $id . '">';
echo strtoupper($page) . '</a>';
}
echo '</ul>';
}
<?php
function myFunction($text){
return md5($text);
}
$array = array(myFunction("Text to be MD5"), myFunction("More Sample Text"));
foreach($array as $value){
echo $value;
echo "<br>";
}
?>
Is this what you were looking for?
you can put the output of a function into an array
Output:
d41d8cd98f00b204e9800998ecf8427e
a95486400f22cfa1ce6ae3a8cacae1e4
So I am using Codeignitor and I am trying to figure out the best way to share my constants with my javascript in a neat maintainable way.
1) in the view I could echo out my variables in like my footer (yuuuck!)
2) I could parse a partial view which contains a template for javascript and inject that in my view (maybe?)
3) I could dynamically create a javascript file like myJavascript.js.php and include that in my header.
What's the best maintainable way to implement PHP into JS in a MVC framework?
To keep my variables nicely wrapped I use a JSON object - that way I won't incur in issues with encoding, slashes, having to manually update the JavaScript every variable I add...
$variables_to_view['js_variables']['var_name'] = $var_name;
then pass it to the view
php_variables = <?php echo json_encode($js_variables) ?>;
alert(php_variables.var_name);
There doesn't seem to be anything wrong about echoing your variables in the script tag. In fact, frameworks like BackboneJS are encouraging you to do so for data you need to pass to your client-side code.
You can use short tag like this:
For Example:
You want to use $abc variable in js, then you will need to write this in js
var abc = <?=$abc?>;
You can create php file .
Something like script.js.php?outfor=1;
<?php
header("Content-type:text/javascript"); //can be application/javascript.
?>
ABC = <?php echo $abc?>
CBA = <?php echo $cba?>
BAC = <?php echo $bac?> //and so on.
Some additional info .
If you use "var" in function that variable will be visible only in that function and without "var"means global.
So.
function abc()
{
var a = 1; //only in abc()
b=2; //global
}
I know that in terms of programming skills it's not the best, but finally it's what I use and it's working. To make it short: I put all my constants in a xml file and I have this little script that generates two separate files with the same content, but different syntax. I am just pasting the code with my values. If it's useful for anybody, I'll be very happy to help.
The xml is the simplest possible; value
<?php
define("GECOXML_PATH","../xml/geco.xml");
define("PHP_GECO_FN","../.includes/geco.php");
define("JS_GECO_FN","../js/geco.js");
echo "******** GECO (GEnerate COnstants files for PHP and JS) **********<br>";
echo "<br>";
echo " input xml file: ". GECOXML_PATH."<br>";
echo " output php file: ". PHP_GECO_FN."<br>";
echo " output js file: ". JS_GECO_FN."<br>";
echo "********************************************************************<br>";
$geco = (object)xmlParse(GECOXML_PATH);
echo "<br>";
echo "<br>";
echo "************ PHP GECO ************* <br>";
echo "<br>";
$PHP = gecoPHP($geco);
echo "<br>";
echo "<br>";
echo "************** JS GECO ************<br>";
echo "<br>";
$JS = gecoJS($geco);
writeFiles($PHP, $JS);
//****** Functions *********
function xmlParse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
return simplexml_load_string($fileContents);
}
function writeFiles($PHPcontent, $JScontent)
{
echo "<br> PhP ok:". file_put_contents(PHP_GECO_FN, $PHPcontent) . "<br>";
echo "<br> JS ok:" . file_put_contents(JS_GECO_FN, $JScontent) . "<br>";
}
function gecoPHP($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "define(\"" . $key . "\",". intval($value) . ");\n";
}
else
{
$line = "define(\"" . $key . "\",\"". $value . "\");\n";
}
$phpContent = $phpContent . $line;
echo $line."<br>";
}
return "<?php\n"$phpContent."?>";
}
function gecoJS($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "var " . $key . "=". $value . ";\n";
}
else
{
$line = "var " . $key . "=\"". $value . "\";\n";
}
$JSContent = $JSContent . $line;
echo $line."<br>";
}
return $JSContent;
}
?>
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;
}