Reputation: 3937
I think what I'm trying to do must be impossible; incredibly difficult; or pretty easy, and I just don't know how to express what I want correctly to Google.
What I want to do is the following:
For the purposes of templating, I am outputting HTML to a file. However, I want the file to contain PHP tags - not the parsed value of the PHP code (this value will change based upon included scripts in the output file) - but the actual <?php ?>
tags themselves - containing the unmodified code, such that the code is still executable at run time.
This is an example of what I want to get outputted:
<html>
<body>
<img src="<?php echo IMG_PATH;?>img.jpg" />
</body>
</html>
What I'm getting is a combination of things that are wrong, depending on which method I use. Basically, I need to be able to write parsable PHP code to a HTML file. Now, whether or not this is a good idea is debatable, and a subject I'm not too interested in at the moment. I just want to know if a sane solution exists.
I came up with the following insane solution:
$content='<html><body><img src="zxzxzx?php echo IMG_PATH; ?qjqjqj" />';
file_put_contents($file,$content);
$command='perl -p -i.bktmp -e "s/zxzxzx/</g" '.$file.' 2>'.$path.'error.log';
$command2='perl -p -i.bktmp -e "s/qjqjqj/>/g" '.$file.' 2>'.$path.'error.log';
exec($command);
exec($command2);
Now, on one hand, this feels devilishly clever. And, it also feels insane. Is there a better/possible way to do this?
Upvotes: 0
Views: 535
Reputation: 360592
You are misinterpreting how PHP operates. The following code:
<?php
echo 'This string <?php echo 'contains' ?> some PHP code';
Will produce as output
This string <?php echo 'contains' ?> some PHP code
You will NOT get:
This string contains some PHP code
PHP's parser is not recursive. PHP code embedded inside PHP code, e.g. inside a string, as it is above, is NOT treated as PHP code - it'll just be some text.
If you want to write out some PHP code, then just write it out:
$string = 'This string <?php echo 'contains' ?> some PHP code';
file_put_contents('file.php', $string);
You don't need to take any special measures for the PHP code in the string to be written out, it'll just "work".
Now, that being said, if you ever put that string into a context where it COULD be evaluated as code, e.g.
eval($string);
then you WILL have to take measures to keep PHP from seeing the opening <?php
tag and switching into "code mode".
Upvotes: 3
Reputation: 2604
Instead your HTML file needs to be a PHP file. See below:
File: test.php
<html>
<head>
</head>
<body>
<? echo 'My PHP embedded in HTML'; ?>
<img src="<? echo $imagePath; ?>"/>
</body>
</html>
Upvotes: 0