when I have a value like this in the database (\"foo\")
how can I echo it without any conflict with html code
notice
htmlspecialchars() basically, for example
<input type="text" value="<? echo htmlspecialchars($value, ENT_QUOTES); ?>" />
The ENT_QUOTES is optional and also encodes the single quote ' .
I used $value since I'm not sure what exactly you have in the database (with or without quotes?) but it will sit in some kind of variable if you want to use it anyway, so, I called that $value.
Since the above is a bit unwieldy I made a wrapper for it:
// htmlents($string)
function htmlents($string) {
return htmlspecialchars($string, ENT_QUOTES);
}
So you can
<input type="text" value="<? echo htmlents($value); ?>" />
Not to be confused with the existing htmlentities(), which encodes all non-standard characters. htmlspecialchars() only encodes &, <, >, " and ', which is more appropriate for UTF8 pages (all your webpages are UTF8, right? ;-).
<?php
echo "<input type='text' value='{$foo}' />" ;
?>
use urlencode or htmlspecialchars
<a href="<?php echo urlencode($dburl)?>" title="<?php echo htmlspecialchars($dbvalue)?>">link</a>
First, don't use short tags ('
Next, your HTML is malformed because you've got an extra set of quotes. Since you seem to be taking the approach of embedding PHP into the HTML, then a quick fix is:
<input type="text" value="<?php echo 'foo'; ?>" />
...although since this value is coming from your database it will be stored in a variable, probably an array, so your code should look more like:
<input type="text" value="<?php echo $db_row['foo']; ?>" />
For clarity, most programmers would try to eliminate switching between PHP parsed and non-parsed code either using a template system like smarty or....
<?php
....
print "<input type='text' value='$db_row[foo]' />\n";
....
?>
(Note that
1) when the variable is within double quotes with a block of PHP, the value is automatically substituted
2) when refering to an associative array entry within a double quoted string, the index is NOT quoted.
HTH
C.
You can use htmlentities to overcome this problem like so:
<input type="text" value="<? echo htmlentities('"foo"'); ?>" />
this will return
<input type="text" value=""foo"" />
avoiding any conflict with html.