Created
May 11, 2011 19:39
-
-
Save originell/967159 to your computer and use it in GitHub Desktop.
XHTML 1.1 form to PHP Array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
""" | |
Convert a XHTML 1.1 compliant form to a php array with Python (YIKES! :D) | |
""" | |
import re | |
# Put your form in here! | |
s = """ | |
<form action="foobar.php" method="post" accept-charset="utf8"> | |
<p> | |
<label for="this">This</label> | |
<input type="text" name="this" id="this" /> | |
</p> | |
<p> | |
<label for="that">That</label> | |
<textarea name="that" id="that"></textarea> | |
</p> | |
<p> | |
<label for="like">Like</label> | |
<input type="file" name="like" id="like" /> | |
</p> | |
<p> | |
<label for="gibberish">Gibberish</label> | |
<select name="gibberish" id="gibberish"> | |
<option value="0">0</option> | |
<option value="1">1</option> | |
</select> | |
</p> | |
</form> | |
""" | |
nodes = re.split('<|>|/(\w+)>|/>', s) | |
attribute_trees = [] | |
for node in nodes: | |
try: | |
# TODO: select->option parsing | |
if 'input' in node or 'textarea' in node or 'select' in node: | |
# only parse nodes with 'name' in them | |
# those are the ones we want for our PHP array | |
if 'name' in node: | |
tag_tree = node.split() | |
# isolate the tagname | |
attributes = tag_tree[1:] | |
# create a list full of [attribute, value] trees | |
attribute_trees.append(map(lambda x: x.split('='), attributes)) | |
# it may happen that we have something which is not a string on l19 | |
except TypeError: | |
pass | |
# Create our PHP array | |
php = 'array(' | |
setComma = False | |
for attribute_tree in attribute_trees: | |
for attribute, value in attribute_tree: | |
# usually only ´name´ matters | |
if attribute == 'name': | |
# set commas after the first element | |
if setComma: php += ', ' | |
# don't put "", so php doesn't try to search for something in namespace | |
php_value = value.replace('"', "'") | |
# add it to our php array string | |
php += '%s => $_POST[%s]' % (php_value, php_value) | |
# now we want to set commas :) | |
setComma = True | |
php += ')' | |
print php |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment