Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a value of an HTML input tag using PHP

Tags:

html

php

extract

I know regex isn't popular here, what is the best way to extract a value of an input tag within an HTML form using a php script?

for example:

some divs/tables etc..

<form action="blabla.php" method=post>

<input type="text" name="campaign">  
<input type="text" name="id" value="this-is-what-i-am-trying-to-extract">

</form>

some divs/tables etc..

Thanks

like image 879
Jim Avatar asked Jul 14 '10 19:07

Jim


People also ask

How can I get input field value in PHP without submit?

How do you get input field value in PHP without submit? Using JavaScript we can get the element. Or you can also use jquery to access the value. by using id = "something" and retrieve it using $('#something').

How do we take input in PHP?

Method 1: Using readline() function is a built-in function in PHP. This function is used to read console input.

Can PHP collect form data?

The PHP superglobals $_GET and $_POST are used to collect form-data.


2 Answers

If you want to extract some data from some HTML string, the best solution is often to work with the DOMDocument class, that can load HTML to a DOM Tree.

Then, you can use any DOM-related way of extracting data, like, for example, XPath queries.


Here, you could use something like this :

$html = <<<HTML
    <form action="blabla.php" method=post>

    <input type="text" name="campaign">  
    <input type="text" name="id" value="this-is-what-i-am-trying-to-extract">

    </form>
HTML;


$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$tags = $xpath->query('//input[@name="id"]');
foreach ($tags as $tag) {
    var_dump(trim($tag->getAttribute('value')));
}

And you'd get :

string 'this-is-what-i-am-trying-to-extract' (length=35)
like image 146
Pascal MARTIN Avatar answered Oct 30 '22 06:10

Pascal MARTIN


$html=new DOMDocument();
$html->loadHTML('<form action="blabla.php" method=post>
    <input type="text" name="campaign">  
    <input type="text" name="id" value="this-is-what-i-am-trying-to-extract">
    </form>');

$els=$html->getelementsbytagname('input');

foreach($els as $inp)
  {
  $name=$inp->getAttribute('name');
  if($name=='id'){
    $what_you_are_trying_to_extract=$inp->getAttribute('value');
    break;
    }
  }

echo $what_you_are_trying_to_extract;
//produces: this-is-what-i-am-trying-to-extract
like image 43
JAL Avatar answered Oct 30 '22 08:10

JAL