开发者

PHP not displaying correctly in HTML

I'm trying to create a drop down box that is populated by an array. When I view my code the browser just displays pieces of the php code.

Here is what the browser displays:

'; foreach ($array as $value) { $html .= '
$value
'; } $html .= ''; return $html; } ?> 

Here is my code:

<html>
<head>
<title>test</title>
<?php

$cities = array( 'San Francisco', 'San Diego', 'Los Angeles');

function createDropDown($name, $array) {

  $html = '<select name=$name>';

  foreach ($array as $value) {
    $html .= '<option value="$value">$value</option>';
  }
  $html .=开发者_StackOverflow '</select>';
  return $html;
}
?>
</head>
<body>
<form>

<?php
createDropDown("cities", $cities);
?>

</form>
</body>
</html>


You need to echo your output as well. You build the string but never output.

<html>
<head>
<title>test</title>
<?php

$cities = array( 'San Francisco', 'San Diego', 'Los Angeles');

function createDropDown($name, $array) {

  $html = '<select name="' . $name . '">';

  foreach ($array as $value) {
    $html .= '<option value="' . $value . '">' . $value . '</option>';
  }
  $html .= '</select>';
  return $html;
}
?>
</head>
<body>
<form>

<?php
echo createDropDown("cities", $cities);
?>

</form>
</body>
</html>


Most likely your server isn't configured to treat .php files as PHP scripts, and is serving them up as html/plaintext. If you view-source the page this is happening on, you'll probably get the full PHP source code. The <?php is seen as an opening HTML tag, which isn't closed until just before the foreach loop, so all the intermediate text/code is "hidden" in HTML view.


Change

$html = '<select name=$name>';

to

$html = '<select name="' . $name. '">';

Change

$html .= '<option value="$value">$value</option>';

to

$html .= '<option value="' . $value . '">' . $value. '</option>';


' doesn't parse, but " does.

 $html = "<select name=$name>";

will do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜