【问题标题】:Get name of an HTML element with PHP parsing使用 PHP 解析获取 HTML 元素的名称
【发布时间】:2017-11-29 17:35:02
【问题描述】:

假设我有一个这样的 HTML 页面。

<input type="text" name="name" />
<input type="hidden" name="test" value="test_result1" />
<input type="hidden" name="test2" value="test_result2" />

我想解析那个 HTML 页面(从一个 url,使用 file_get_contents?),然后获取类型为“隐藏”的输入元素的名称。

基本上我想从该页面解析的是

test
test2

有没有办法做到这一点?我查看了一些解析库(如 SimpleHTMLDom),但我做不到。

【问题讨论】:

  • 你找对地方了,你只需要学习如何使用它。
  • @JayBlanchard 不应该是这样的吗? $html-&gt;find('input[type=hidden]');
  • @JayBlanchard 当我这样做时,我得到的是完整的行,而不是它的名称,你能告诉我在哪里看吗?

标签: php html parsing


【解决方案1】:

使用 SimpleHTMLDom

$html = file_get_html('http://www.google.com/');

// Find all inputs
foreach($html->find('input') as $element){ 
    $type = $element->type;
    if($type=='hidden'){
        echo $element->name. '<br/>';
    }
}

【讨论】:

    【解决方案2】:

    使用 php DOMDocument。

    $html = "<html>
            <body>
                <form>
                    <input type='text' name='not_in_results'/>
                    <input type='hidden' name='test1'/>
                    <input type='hidden' name='test2'/>
                </body>
            </html>";
    
    $dom = new DOMDocument;
    $dom->loadHTML($html);
    $inputs = $dom->getElementsByTagName('input');
    
    $hiddenInputNames = [];
    
    foreach ($inputs as $input) {
        if($input->getAttribute('type') == "hidden")
            $hiddenInputNames[] = $input->getAttribute('name');
    }
    
    var_dump($hiddenInputNames);
    

    【讨论】:

      【解决方案3】:

      试试这个:

      include 'simple_html_dom.php';
      $data = file_get_html('index.html');
      $nodes = $data->find("input[type=hidden]");
      foreach ($nodes as $node) {
        $val = $node->name;
        echo $val . "<br />";
      }
      

      输出:

      test
      test2
      

      在这种情况下,您必须包含php simple html dom par

      【讨论】:

        【解决方案4】:

        simple_html_dom 很容易使用,但也很老,速度也不是很快。使用 php 的 DOMDocument 要快得多,但也没有 simple_html_dom 简单。另一种选择是DomQuery 之类的东西,它基本上让您可以像访问 php 的 DOMDocument 一样访问 jquery。这很简单:

        $dom = new DomQuery(file_get_html('index.html'))
        foreach($dom->find('input[type=hidden]') as $elm) {
            echo $elm->name; 
        }
        

        【讨论】:

        • 这个问题有几个月前的公认答案,不确定这对讨论有多大价值。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-06
        • 1970-01-01
        • 2011-08-22
        • 2020-10-24
        • 2011-11-07
        • 2022-01-04
        • 2018-11-12
        相关资源
        最近更新 更多