Search code examples
phpescapingquotesdouble-quotes

php having issue with including javascript and quotes?


Here is my code:

$buffer .= '<legend>'.$thisField.'</legend><input type="text" name="'.$thisField.'" id="'.$thisField.'"/> <a href="javascript:;" onClick="mcImageManager.browse({fields : 'url_abs'});">[Pick file]</a><br /><small>360px W x 240px H</small><br /><br />';

It is breaking syntax error, unexpected T_STRING

I have tried every type of combination of single quotes, double quotes and escaping ??

I am at a loss, What am I missing??

Thanks!!


Solution

  • In such cases it's advisable to resort to HEREDOC strings, also for readability:

    $buffer .= <<<END
      <legend>$thisField</legend>
      <input type="text" name="$thisField" id="$thisField"/>
      <a href="javascript:;" onClick="mcImageManager.browse({fields : 'url_abs'});">[Pick file]</a>
      <br /><small>360px W x 240px H</small><br /><br />
    END;
    

    This avoids having to escape any quotes. And you can just write $variables as-is within such a block.