You can use output buffering to achieve something similar, although it's not possible to directly embed PHP code in JS.
Example:
server.php
<?php
echo 'hello World';
?>
client.php - (.php extension enables the ability to parse PHP tags, but really outputs JS)
<?php
header("Content-type: application/x-javascript"); // Or 'text/javascript'
ob_start();
include( 'server.php');
$i = ob_get_contents();
ob_end_clean();
?>
function foo() {
var i = '<?= json_encode( $i); ?>';
console.log( i );
}
Edit:
If the server.php file will only return a simple string, then you can modify your code for client.php. Notice how I said "return" instead of output - If your server.php outputs anything, it will be sent to the browser as output (not what you want). Alternatively, you can set a variable in server.php which gets outputted in client.php, or encapsulate your code in a function:
server.php
<?php
function js_output()
{
return 'hello world';
}
?>
client.php
<?php
header("Content-type: application/x-javascript"); // Or 'text/javascript'
?>
function foo() {
var i = '<?php include( 'server.php'); echo addslashes( js_output()); ?>';
console.log( i );
}
Note: You may also want to add a call to html_entities
or htmlspecialchars
.