在PHP代码中连接

时间:2015-10-01 23:52:46

标签: php concatenation

我尝试过连接文本框输入的几种不同变体,但都没有奏效。任何人都可以通过向我展示如何在一行(背靠背)连接所有这些?

HTML

<form method="post" action="sample.php">

<p>My Information
<br />City State  <input type="text" name="item1" size="30">
<br />State Name   <input type="text" name="item2" size="30">
<br />County Name    <input type="text" name="item3" size="30">

</p>

<input type="submit" value="Submit Information">

</form>

PHP

<?php

print "<h4>Geographic Location<b/h4>>";
$filename = 'data/'.'sample.txt';
$fp = fopen($filename, 'w');   //w opens the file for writing
$cntr = 1;
while(true)
{
    $item_name = 'item'.$cntr;
    $item = $_POST[$item_name];
    if (empty($item))
    {
        break;
    }
    $cntr++;
    print "Item: ".$item."<br />";
    $output_line = $item."\n";
    fwrite($fp, $output_line);
}

1 个答案:

答案 0 :(得分:1)

假设这是整个表格,这可以大大简化,不需要任何循环:

print "<h4>Geographic Location<b/h4>>";
$filename = 'data/'.'sample.txt';
$fp = fopen($filename, 'w');   //w opens the file for writing
$output_line = $_POST['item1'].' '.$_POST['item2'].' '.$_POST['item3']; //create the string to write to file 
print "Item: ".$output_line."<br />"; //display to the user
fwrite($fp, $output_line); //write to the file

建议将第1-3项更改为更具描述性的名称