H. Pauwelyn
H. Pauwelyn

Reputation: 14310

How can you get all inputs fields and the value

How can you get all the input fields where type="text" from a HTML form with php? This is my code:

if (isset($_POST['submit'])) {
    $dom = new DOMDocument();
    print "<pre>";

    foreach($dom->getElementsByTagName("input") as $inputs) {

        print $inputs->value . " / " . $inputs->name . "<br/>";
    }

    print "</pre>";
}

I would also get from every input field the name and the value. If I run my code, I get nothing. Here is my html code:

<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post">
    <input name="1" type="text" value="Can you help me?"/>
    <input name="2" type="text" value="Thanks"/>
    <input name="3" type="text" value=""/>
    <!--and a lot more input fields.-->

    <input name="submit" type="submit" value=""/>
</form>

I'm really new with php and DOM.

Upvotes: 1

Views: 4003

Answers (3)

Professor Abronsius
Professor Abronsius

Reputation: 33813

Using DOMDocument you could call an xpath query to find the elements like:-

        $str='
        <form action="" method="post">
            <input name="1" type="text" value="Can you help me?"/>
            <input name="2" type="text" value="Thanks"/>
            <input name="3" type="text" value=""/>
            <!--and a lot more input fields.-->
            <select name="fred"><option value=1>1</select>
            <input type="checkbox" name="bert" value=1>
            <input type="radio" name="wilma" value=1 />
            <textarea name="sue"></textarea>
            <input name="submit" type="submit" value=""/>
        </form>';   

        $dom = new DOMDocument;
        $dom->loadHTML( $str );
        $xpath = new DOMXpath( $dom );
        $col=$xpath->query('//form/input|//form/textarea');

        if( is_object( $col ) ){
            foreach( $col as $node ) echo $node->tagName.' '.$node->nodeValue.'<br />';
        }

You can extend the xpath query by using the pipe character and then specifying a new query, for instance |//form/button etc

To get specific fields where the type is text, the query would be:-

$col=$xpath->query('//form/input[@type="text"]');

Upvotes: 1

Alex Kobzin
Alex Kobzin

Reputation: 69

Why just not to combine input elements with their names like

<input name="text[3]" type="text" value=""/>
<input name="text[4]" type="text" value=""/>

It will come in $_POST as array

Upvotes: 1

Farhan
Farhan

Reputation: 1483

This might help you

$data = $_REQUEST;
unset($data["submit"]);
print_r($data);

Upvotes: 2

Related Questions