2017-02-15 43 views
0

所以說我有一個這樣的HTML頁面。用PHP解析得到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),但我無法做到。

+0

你看在正確的地方,你只需要學習如何使用它。 –

+0

@JayBlanchard不應該是這樣的嗎? '$ html-> find('input [type = hidden]');' – user6613235

+0

@JayBlanchard當我這樣做的時候,我得到了整條線,而不是它的名字,請問你能告訴我在哪裏看? – user6613235

回答

3

使用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/>'; 
    } 
} 
+0

非常完美,非常感謝 – user6613235

0

使用PHP DOM文檔。

$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); 
0

試試這個:

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

0

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; 
} 
+3

這個問題有幾個月前接受的答案,不知道這會增加多少價值的討論。 –