Trying not to reinvent the wheel. Is there a function around that does this?

Discussion in 'PHP' started by meroving, Jan 27, 2010.

  1. #1
    Loops through a form and pulls out all input/selection drop-downs/etc and places their name and value into an array? I can build it but don't want to spend the 2-3 hours (maybe more?) doing it if it already exists. Anyone seen such a function?

    
    $html = file_get_contents('http://www.website_with_a_big_form.com/index.php');
    
    $form = getFormElements($html);
    
    print_r($form);
    
    /* Output:
    array(
    'inputName1'=>'inputValue1',
    'inputName2'=>'inputValue2',
    'inputName3'=>'inputValue3',
    'inputName4'=>'inputValue4',
    'inputName5'=>'inputValue5'
    )
    */
    
    
    
    Code (markup):
     
    meroving, Jan 27, 2010 IP
  2. meroving

    meroving Peon

    Messages:
    135
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Well I went ahead and built the first part, so far it only does inputs. I will make it do selects and textareas tomorrow. (I also have to make it work when there are spaces between the equal sign)

    
    
    function getStringBetween($string, $start, $end){ 
    	    $string = " ".$string; 
    	    $ini = strpos($string,$start); 
    	    if ($ini == 0) return ""; 
    	    $ini += strlen($start); 
    	    $len = strpos($string,$end,$ini) - $ini; 
    	    return substr($string,$ini,$len); 
    	}
    
    function getFormElements($html){
    		$formTags = array(
    		1=>array('start'=>'<input','end'=>'>'),
    		2=>array('start'=>'<select>','end'=>'</select>'),
    		3=>array('start'=>'<textarea>','end'=>'</textarea>')
    		);
    		$sourceHtml = $html;
    		foreach($formTags as $formTag){
    			$html = $sourceHtml;
    			if($formTag['start'] == '<input'){
    				while(($startPosition = strpos($html, $formTag['start'])) > 0){
    					$input = $this->getStringBetween($html,$formTag['start'],$formTag['end']);
    					$explodedTag = explode(' ',trim($input));
    					ksort($explodedTag);
    					foreach($explodedTag as $tag){
    						$capsule = $tag[strlen($tag)-1];
    						$attrValue = explode('=',$tag);
    						if($attrValue[0]=='name'){
    							$key = $this->getStringBetween($attrValue[1],$capsule,$capsule);
    						}
    						if($attrValue[0]=='value'){
    							$value = $this->getStringBetween($attrValue[1],$capsule,$capsule);
    							$form[$key] = $value;
    							$html = substr($html,strpos($input)+strlen($input));
    							break;
    						}
    					}
    				}
    			}
    		}
    	}
    
    
    Code (markup):
     
    Last edited: Jan 27, 2010
    meroving, Jan 27, 2010 IP