How to use javascript inside a PHP echo function?

2019-01-29 01:33发布

I want to echo out a simple Facebook like button script in PHP, but it wont let me. Here's what the script would look like:

<?php
  echo "    <td>'<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http://#" layout="button_count" show_faces="false" width="450" font=""></fb:like>'</td>\n" ;        
  echo "    <td>".$row['item_content']."</td>\n";    
?>

3条回答
对你真心纯属浪费
2楼-- · 2019-01-29 01:39

You have to properly escape your quotation marks.

Everytime you are using a double-quote (") in a double-quoted string, you must prepend it with a backslash (\) as such:

echo "    <td>'<script src=\"http://connect.facebook.net/en_US/all.js#xfbml=1\"></script><fb:like href=\"http://#\" layout=\"button_count\" show_faces=\"false\" width=\"450\" font=\"\"></fb:like>'</td>\n";
echo "    <td>".$row['item_content']."</td>\n";

Alternatively, you could single-quote (') the whole string, but note that in single-quoted strings, the only escape sequences recognized are \' and \\. In-line variables are also not recognized.

echo '    <td>\'<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http://#" layout="button_count" show_faces="false" width="450" font=""></fb:like>\'</td>' ;
echo "\n    <td>".$row['item_content']."</td>\n";

For more information, please read the PHP Documentation page on Strings:

PHP Documentation: Strings

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-29 01:47

Is this the complete code? Better is not to echo it at all:

<td>
    <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
    <fb:like href="http://#" layout="button_count" show_faces="false" width="450" font=""></fb:like>
</td>
<td><?php echo $row['item_content']; ?></td>

Embed PHP in HTML, not vice versa.

查看更多
萌系小妹纸
4楼-- · 2019-01-29 01:55

Try this, you must escape some symbols

<?php
       echo '    <td>\'<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http://#" layout="button_count" show_faces="false" width="450" font=""></fb:like>\'</td>\n';
echo "    <td>".$row['item_content']."</td>\n";

?>
查看更多
登录 后发表回答