Read From an Array and Create Form

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hotrod57
    New Member
    • Oct 2007
    • 7

    #1

    Read From an Array and Create Form

    I have a text file that is changeable that I want to use to create a form with. Here is my text file, called 'test_read.txt" :

    Code:
    title = Test Form;
    checkbox = shoe;
    checkbox = hair;
    radio_button = 3;
    comment_box
    dropbox = 18-29;
    dropbox = 30-49;
    dropbox = 50-75;
    textbox = 50;
    Now my PHP code, right now, is just supposed to print the info out for test purposes. My problem is that it only prints the two checkboxes with no values for them. My next question is can I put the <form></form> tags in this same file, or will I need to create another file for it? Here is my PHP code:

    [PHP]<?php
    $lines = file('test_read .txt');

    foreach ($lines as $line) {
    list($field, $value) = explode("=", $line);

    $value = substr(trim($va lues), 0, 1);
    echo get_html($field , $value);

    }

    function get_html($tag, $value) {
    switch(trim($ta g)) {
    case 'checkbox':
    return "<input type=\"checkbox \" name=\"userbox\ " value=\"$value\ ">$value";
    break;

    case 'radio':
    return "<input type=\"radio\" name=\"userbox\ " value=\"$value\ ">$value";
    break;
    // more cases below if needed.
    }
    }
    ?>[/PHP]
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    That code should work fine, with two minor exceptions.

    First, this line doesn't make sense to me:
    [code=php]
    $value = substr(trim($va lues), 0, 1);
    [/code]
    What is this supposed to do? Does a variable called $values even exist in your code?

    Second, the fields and the values you have there could both include white-spaces on each side. I would use the trim() function to clean both of them before using them.

    As to the <form> fields. You can add them directly into the PHP code, before and after the foreach loop.
    You could also add them to the text file and add a case to you switch that handles them.

    In this particular case, I would go with the second option.

    Comment

    • w0rKInPHP
      New Member
      • Oct 2007
      • 6

      #3
      do it this way and it will work
      Code:
      list($field, $value) = explode(" = ", str_replace(";", "", $line));
      and fix your $values variable, which if you do it this way, you won't need to trim it because the explode is taking consideration of the white space.

      Comment

      Working...