phpinputhtmlspecialchars

Echo string containing single and double quotes to input value


I'm extracting a string from XML and want to insert it as the value of an input text box. And I'm having problems with this string containing both single and double quotes:

We will have a "New Year's Eve countdown"

Here is the code I'm using to output this. I've tried using htmlspecialchars but it doesn't stop the html code breaking because of the mix of quotes in the string.

echo "<p>Info <input type='text' name='info' value='".htmlspecialchars($result->info)."' size='20' /></p>";

How can I fix this so that it correctly displays the value of the string in the text box?


Solution

  • You need to use the ENT_QUOTES flag to htmlspecialchars to get it to convert both double and single quotes to their html entity equivalent:

    echo "<p>Info <input type='text' name='info' value='".htmlspecialchars($result->info, ENT_QUOTES)."' size='20' /></p>";
    

    This will produce the following HTML:

    <p>Info <input type='text' name='info' value='We will have a &quot;New Year&#039;s Eve countdown&quot;' size='20' /></p>
    

    Which as you can see from this snippet, displays the desired string in the text input:

    <p>Info <input type='text' name='info' value='We will have a &quot;New Year&#039;s Eve countdown&quot;' size='50' /></p>