1

I think it is sometimes easier to use php tags instead of echo for example

<?
if()
    echo "<img src='' onclick='alert(\"hello\")'/>";
?>

instead of that I code like this

<?
if(){
?>
<img src='' onclick='alert("hello")'/>
<?}
?>

We got rid of backslashing. But what about strings I want something like this:

<?
$str="?>
   <img src='' onclick='alert("hello")'/>
<?";
?>
3
  • Can you explain what you're trying? Commented Jul 27, 2014 at 12:48
  • Yes, I use the second form. For the third example, store the snippet in an HTML file and load it in using file_get_contents. Commented Jul 27, 2014 at 12:48
  • I want to put img tag in $str; Commented Jul 27, 2014 at 12:54

2 Answers 2

6

You should use the PHP heredoc syntax:

<?php
$str = <<<IMGTAG
 <img src="" onclick="alert('hello')"/>
IMGTAG;

echo $str;
?>

Enjoy your code.

Sign up to request clarification or add additional context in comments.

Comments

1

There is an alternative Syntax specifically for this kind of formation:

<?php if (x): ?>
<div>...</div>
<?php endif; ?>

Also there are short tags:

<?= "hello world" ?>

This directly prints a string and is equal to:

<?php echo "hello world" ?>

For string assignment you can do what Magicianred sugested. You could also do it with output buffering:

<?php ob_start(); ?>
<div>test</div>
<?php 
$str = ob_get_contents();
ob_end_clean();
echo $str;
?>

Though output buffering shouldn't be abused for this. Heredoc syntax is the best solution here.

1 Comment

I think the OP was asking how to do this with string assignments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.