What is the best way to echo results from the data

2019-02-19 23:34发布

when I have a value like this in the database ("foo")

how can I echo it without any conflict with html code

notice

<input type="text" value="<? echo '"foo"'; ?>" />

the result will be like this

<input type="text" value=""foo"" />

how can I fix it ?

5条回答
手持菜刀,她持情操
2楼-- · 2019-02-20 00:07

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? ;-).

查看更多
男人必须洒脱
3楼-- · 2019-02-20 00:25

You can use htmlentities to overcome this problem like so:

<input type="text" value="<? echo htmlentities('"foo"'); ?>" />

this will return

<input type="text" value="&quot;foo&quot;" />

avoiding any conflict with html.

查看更多
混吃等死
4楼-- · 2019-02-20 00:25

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.

查看更多
贼婆χ
5楼-- · 2019-02-20 00:29

use urlencode or htmlspecialchars

<a href="<?php echo urlencode($dburl)?>" title="<?php echo htmlspecialchars($dbvalue)?>">link</a>
查看更多
淡お忘
6楼-- · 2019-02-20 00:29
<?php

echo "<input type='text' value='{$foo}' />" ;

?>
查看更多
登录 后发表回答