14 February, 2011

How to get all hidden elements from a form using php

I always had problem getting all the hidden elements of a form when using cURL. So thought of making a function that extracts all the hidden elements from a form when passed as a string.
Here's the function

function getHidden($form) {
$hiddenElements="";
$doc=new DOMDocument();
$doc->loadHTML($form);
$xpath=new DOMXPath($doc);

//use xPATH for quering the hidden elements in a form passes as string $form
$qry="//input[@type='hidden']";
$xData=$xpath->query($qry);

//loop thru all the data
foreach($xData as $value) {
//typecast the name and values as string to avoid xml object
$eleName=(string) $value->getAttribute('name');
$eleValue=(string) $value->getAttribute('value');
$hiddenElements[$eleName]=$eleValue;
}
return $hiddenElements;
}

?>

And thats it. The above function can be useful while doing a cURL using php to get form fields. Hope this helps someone

No comments: