How to echo an echo in php? - php

I have some basic PHP code:
$raceramps56["short"] = "My Test Product";
$leftMenu =
'<div class="leftMenuProductButton"><?PHP echo $raceramps56["short"] ?></div>';
Won't echo the PHP code, only the element. I've tried things like
<div class="leftMenuProductButton">' . <?PHP echo $raceramps56["short"] ?>. '</div>';
Which just returns Parse error: parse error, unexpected '<'
So my question is, how do I either get this to work, or take another approach?

try this
$raceramps56["short"] = "My Test Product";
$leftMenu ='<div class="leftMenuProductButton">'.$raceramps56["short"].'</div>';

I thought I'd provide some extra information just so you understand.
In your code:
$raceramps56["short"] = "My Test Product";
$leftMenu =
'<div class="leftMenuProductButton"><?PHP echo $raceramps56["short"] ?></div>';
You are including literally.
Take a read of this. http://php.net/manual/en/language.types.string.php
When I was first learning, I did not understand the different between literal ' and double quotes and it especially caused problems when I was trying to echo things.
Take a look at this:
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
If you were to use " " instead of ' you would not get the same output because " will interpret everything rather then take it literally.
I hope this has been of additional help, even though you have had your question answered already.

You can run php in a '. You can only echo it like this if you know what I mean.
$leftMenu ='<div class="leftMenuProductButton">.$raceramps56["short"].</div>';
echo $leftMenu;
Use this:
$leftMenu ='<div class="leftMenuProductButton">'.$raceramps56["short"].'</div>';

Or without the need of escaping double quotes:
$leftMenu = '<div class="leftMenuProductButton">' . $raceramps56["short"] . '</div>';

$raceramps56["short"] = "My Test Product";
$leftMenu = '<div class="leftMenuProductButton">' . $raceramps56["short"] . '</div>';
echo $leftMenu;

Related

escape character not working as expected

I am trying to create html content in PHP and for onclick event I have included a function named uchat for a div. The function takes a name parameter which is a string.
Like below:
$name = "Php string";
$echostr .= "<div onClick='uchat(\'$name\')'>
</div>";
But, passing a string value like this causes syntax error when div is clicked. Because, single quote is within a single quote. I have tried to escape it, but it still doesnt work.
The error is this:
SyntaxError: illegal character
uchat(\
I am not sure how to escape a string parameter and I have come across this problem so many times, Please help if you have a solution for this.
Thanks.
Escaped single quotes will conflict with outer ones:
$echostr .= "<div onClick=\"uchat('$name')\">
</div>";
Here are 2 clean and simple ways to do this:
1. Classic concat
$name = "Php string";
$str = "<div onClick=\"uchat('" . $name . "')\"></div>";
print $str;
2. Using sprintf (http://us3.php.net/manual/en/function.sprintf.php)
$name = "Php string2";
$str = sprintf("<div onClick=\"uchat('%s')\"></div>", $name);
print $str;
try like this
$echostr .= "<div onClick='uchat("$name")'></div>";
This works:
<?php
$name = "Php string";
$echostr .= <<< EOF
<div onClick="uchat('$name')"></div>
EOF;
echo $echostr;
?>
Output:
<div onClick="uchat('Php string')"></div>
In order to avoid escaping all double quotes and to make the html code more readable you can use EOF.
See it action : http://ideone.com/vRCCVH

Executing Python Script with PHP Variables

I am writing a simple application that uses information from a form, passes it through $_POST to a PHP script that executes a python script and outputs the results. The problem I am having is that my python script is not actually running with the arguments being passed in.
process3.php file:
<?php
$start_word = $_POST['start'];
$end_word = $_POST['end'];
echo "Start word: ". $start_word . "<br />";
echo "End word: ". $end_word . "<br />";
echo "Results from wordgame.py...";
echo "</br>";
$output = passthru('python wordgame2.py $start_word $end_word');
echo $output;
?>
Output:
Start word: dog
End word: cat
Results from wordgame.py...
Number of arguments: 1 arguments. Argument List: ['wordgame2.py']
At the top of my wordgame2.py, I have the following (for debugging purposes):
#!/usr/bin/env python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Why isn't the number of arguments being passed = 3?
(Yes, my form does send the data correctly.)
Any help is greatly appreciated!
Edit: I might add that it does run when I explicitly tell it the start and end word... something like this:
$output = passthru('python wordgame2.py cat dog');
echo $output
Update -
Now that I am aware of PHP, the mistake lies in using the single-quotes '. In PHP, single quoted strings are considered literals, PHP does not evaluate the content inside it. However, double quoted " strings are evaluated and would work as you are expecting them to. This is beautifully summarized in this SO answer. In our case,
$output = passthru("python wordgame2.py $start_word $end_word");
would work, but the following won't -
$output = passthru('python wordgame2.py $start_word $end_word');
Original answer -
I think the mistake lies in
$output = passthru("python wordgame2.py $start_word $end_word");
Try this
$output = passthru("python wordgame2.py ".$start_word." ".$end_word);
Thank you for your contributions. I have figured out my problem with this simple fix:
$command = 'python wordgame2.py ' . $start_word . ' ' . $end_word;
$output = passthru($command);
In order for passthru to properly handle the php variables, it needs to be concatenated into the string before executing.
well if I understood you want pass a big amount of text like content of something, so the right way is;
$output = passthru("python wordgame2.py ".json_encode($end_word)." ".json_encode($start_word));

Weird issue with concatenate variables

I am a weird issue regarding my class property here
I have the following:
$this->tableData = '<table>';
$this->tableData .= $string;
echo $this->tableData => output <table>
I want to concatenate more string to my $this->tableData but it seems like nothing is added.
I know $string is not null and contains characters
Did I do something wrong here?
Thanks!
To see if your string is not null you should use var_dump() or print_r() functions.
Example:
$this->tableData = '<table>';
echo "Dumping tableData: " . var_dump($this->tableData);
$this->tableData .= $string;
echo "Dumping tableData 2: " . var_dump($this->tableData);
echo "Dumping string: " . var_dump($string);
That way you will see exactly what is going on.
Is your variable $string containing a HTML tag, something like <p></p> or else ?
This could be "hidden" if you print_r it inside a browser.

Issues while using Quotes in PHP

I have Learnt that Quotes doesn't matter in PHP.
But in the following code, if I try to use single quotes in eval(); I get error, on the other hand code works fine with Double Quotes.
$a = '2';
$b = '3';
$c = '$a+$b';
echo $c.'<br/>';
eval("\$c = \"$c\";");
//eval('\$c = \'$c\';'); //Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
echo $c;
PHP.net says that escape sequences are not expanded when using single quotes.
Quotes do matter ;-)
<?php
$color = "red";
echo "My car is $color"; // Outputs "My car is red"
echo 'My car is $color'; // Outputs "My car is $color"
?>
Unlike double quotes, PHP does not parse variables in single quotes.
Example:
$name = 'John';
echo 'hello $name'; // hello $name
echo "hello $name"; // hello John
More Information
FYI, it isn't good idea to use eval in production environment for security reasons.
Using eval is a bad idea but if you are doing this for learning purpose then the correct way is
eval("\$c = \$c;");
.
don't use eval and update your string-quoting skills here:
The following example was lifted from: The PHP Manual
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

How to handle newlines in Javascript? (from PHP)

I have code like this:
<?php
echo '<script type="text/javascript">';
echo 'var out="'.$txt.'";';
echo '</script>';
?>
Where $txt is a PHP variable that can contain newlines like this:
line1
line2 hello world
Which would end up like this:
var out="line1
line2 hello world";
Which will cause a Javascript error, of course.
What is the best way to handle this? The out variable will be used in a HTML textarea, so I don't think it can be parsed into <br>
$txt = str_replace( array( "\n", "\r" ), array( "\\n", "\\r" ), $txt );
should replace newlines. Don't do it this way.
This is a naïve implementation of string escaping for JavaScript. As you're actually trying to format a string for use in JavaScript, a much better solution would be to use json_encode:
$txt = json_encode($txt);
echo "<script>var out={$txt};</script>";
json_encode will correctly escape special characters in strings, such as quotes, tabs, form feeds, and other special unicode characters. It will also perform all the correct escaping for converting objects, arrays, numbers, and booleans.
you can add a \ at the end of a line to create a multi line String
var out="line1 \
line2 hello world";
Most of these don't work for me.
Normally, I'd use json_encode like
<?php
$MyVar = json_encode($MyVar);
?>
<javascript language='javascript'>
MyVar = <?php echo $MyVar; ?>
But for a quick fix you can just break a line like this:
Pay attention to the double quotes.
<?php
$MyVar = "line one here
then line two here
finally line five here";
//** OR
$MyVar = $MyVarA .
"
"
. $MyVarB;
?>
<HTML>
<HEAD>
<javascript language='javascript'>
Myvar = "<?php echo $MyVar; ?>";
. . .
You can use str_replace to convert line breaks into a different character (in this case, perhaps a space, but it depends how you want the output to show up)
$out = str_replace("\n", '\n', $in);
$content = str_replace( "\\n", "\\\\\\n", $content );
Result:
var a = "Hello \
World"
I tried this and it worked well.
<?php
echo '<script type="text/javascript">';
$txt = "line1 \\n line2 hello world";
echo 'var out="'.$txt.'";';
echo '</script>';
?>
I am using PHP 5.3

Categories