Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting PHP code in a string

Tags:

syntax

string

php

How do I put PHP Code into a string?

$phpCode = '<? if($condtion){ ?>';

For some reason, when I do this and echo out the code, I don't get the opening PHP tag, <?.

Am I missing something? Is there a better or more proper way to do this? I am currently looking at the PHP docs on strings but I would like to get your feedback.

Edit: The reason why I am using apsotrophes (') and not quotes (") is because I don't want the code to fill in the value for condition. I want it to echo as-is.

like image 438
Chris Bier Avatar asked Apr 26 '13 15:04

Chris Bier


People also ask

How do you input a string in PHP?

?> The sscanf() function parses input from a string according to a specified format. The sscanf() function parses a string into variables based on the format string. If only two parameters are passed to this function, the data will be returned as an array.

Can we write PHP inside script?

you can generate JavaScript with PHP in the same way you generate HTML with PHP. Or you can use an AJAX request from JavaScript to interact with the server. The server can respond with data and the JavaScript can receive that and do something with it.

Can I write PHP code in HTML file?

As you can see, you can use any HTML you want without doing anything special or extra in your PHP file, as long as it's outside and separate from the PHP tags. In other words, if you want to insert PHP code into an HTML file, just write the PHP anywhere you want (so long as they're inside the PHP tags).


1 Answers

Use htmlspecialchars():

$phpCode = '<? if($condtion){ ?>';
echo htmlspecialchars($phpCode);
like image 85
John Conde Avatar answered Sep 22 '22 13:09

John Conde