How to use javascript inside a PHP echo function?

2019-01-29 01:28发布

问题:

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";    
?>

回答1:

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.



回答2:

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:

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";

?>