Created
October 29, 2012 19:44
-
-
Save kevinfodness/3976067 to your computer and use it in GitHub Desktop.
A PHP function to get an array of field names and default values from an HTML form on a remote server.
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
<?php | |
/** | |
* Contains a function to get the contents of a live form. | |
* | |
* PHP Version 5.3 | |
* | |
* Requires the allow_url_fopen parameter to be set to true in php.ini. | |
* | |
* @category FormProcessing | |
* @package HTMLFormProcessing | |
* @author Kevin Fodness <[email protected]> | |
* @license http://www.gnu.org/licenses/gpl.html GNU Public License v3 | |
* @link http://www.kevinfodness.com | |
*/ | |
/** | |
* A function to get the contents of a live form. | |
* | |
* @param string $formId The ID attribute of the form to match. | |
* @param string $formUrl The URL where the form can be found. | |
* | |
* @return array An associative array of form fields and default values. | |
*/ | |
function formGetContents($formId, $formUrl) | |
{ | |
/** Get the form as a DOMElement. */ | |
$page = new DOMDocument(); | |
$page->loadHTML(file_get_contents($formUrl)); | |
$form = $page->getElementById($formId); | |
/** Initialize the content array, which contains return data. */ | |
$content = array(); | |
/** Get the INPUT tags. */ | |
$inputNodes = $form->getElementsByTagName('input'); | |
foreach ($inputNodes as $node) { | |
$name = $node->getAttribute('name'); | |
$value = $node->getAttribute('value'); | |
if (strlen($name) > 0) { | |
$content[$name] = $value; | |
} | |
} | |
unset($inputNodes); | |
/** Get the SELECT tags. */ | |
$selectNodes = $form->getElementsByTagName('select'); | |
foreach ($selectNodes as $node) { | |
$name = $node->getAttribute('name'); | |
$options = $node->getElementsByTagName('option'); | |
$length = $options->length; | |
$value = $options->item(0)->getAttribute('value'); | |
for ($i = 0; $i < $length; $i++) { | |
if ($options->item($i)->getAttribute('selected')) { | |
$value = $options->item($i)->getAttribute('value'); | |
} | |
} | |
if (strlen($name) > 0) { | |
$content[$name] = $value; | |
} | |
} | |
unset($selectNodes); | |
/** Get the TEXTAREA tags. */ | |
$textareaNodes = $form->getElementsByTagName('textarea'); | |
foreach ($textareaNodes as $node) { | |
$name = $node->getAttribute('name'); | |
$value = preg_replace( | |
'/<textarea.*?>(.*)<\/textarea>/i', | |
'$1', | |
$node->ownerDocument->saveXML($node) | |
); | |
if (strlen($name) > 0) { | |
$content[$name] = $value; | |
} | |
} | |
unset($textareaNodes); | |
return $content; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment