如何使用PHP提取HTML输入标记的值

时间:2010-07-14 19:15:44

标签: php html extract

我知道正则表达式在这里不受欢迎,使用php脚本在HTML表单中提取输入标记值的最佳方法是什么?

例如:

一些div / table等..

<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>

一些div / table等..

由于

4 个答案:

答案 0 :(得分:14)

如果要从某些HTML字符串中提取一些数据,最好的解决方案通常是使用DOMDocument类,它可以将HTML加载到DOM树。

然后,您可以使用任何与DOM相关的提取数据的方式,例如,XPath查询。


在这里,您可以使用以下内容:

$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')));
}

你会得到:

string 'this-is-what-i-am-trying-to-extract' (length=35)

答案 1 :(得分:2)

$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

答案 2 :(得分:0)

将表单发布到php页面。您想要的值将在$ _POST ['id']中。

答案 3 :(得分:0)

你是什么意思正义表不受欢迎?我喜欢正则表达式。

无论如何,你想要的是:

$contents = file_get_contents('/path/to/file.html');
preg_match('/value="(\w+)"/',$contents,$result);