Is it possible to know the type of a html input with php? [closed]
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
开发者_开发百科Closed 9 years ago.
Improve this questionI need to check the type of the different inputs I have in a form.
I need to know if the field xxx is a checkbox, radio, select, etc.
Is it possible?
Thanks!
- César -
Assuming you mean after submitting the form, then no, only the parameter name and value are sent to the server. You could be a little clever with your naming to identify them server-side. At the server, you can then iterate over the request variables and parse chk
from the name. For example:
HTML
<input type="checkbox" name="chkMyCheck" value="1" />
PHP
foreach ($_GET as $key => $value) {
if (substr($key, 0, 3) == "chk")
echo 'Checkbox '.$key.' submitted with value '.$value;
}
It makes it harder to get the variables at the server, though, if you don't know the type beforehand.
Yes, you can use an HTML parser and fetch the input element's type attribute.
$html = <<< HTML
<form>
<input type="submit" value="Submit"/>
<input type="hidden" value="1234"/>
<input type="text" value="some text" id="xxx"/>
</form>
HTML;
// fetch with
$dom = new DOMDocument;
$dom->loadHTML($html); // use loadHTMLFile to load from file or URL
echo $dom->getElementById('xxx')->getAttribute('type');
will output "text".
There is plenty of examples on SO that cover fetching different parts. Just give it a search.
The only data types that reach PHP are strings and arrays, so it's not possible to do that directly.
The way I see it you only have two options:
- Use Hungarian-like notation, or
- Parse the form DOM with SimpleXML or similar
精彩评论