2016-09-05 45 views
1

我剛開始學習DOM解析器。用DOM解析器提取文本

讓我們假設在http://test.com我有4行像下面的一個,我試圖提取上下文作爲文本。 我需要的只是LPPR 051600Z 35010KT CAVOK 27/14 Q1020作爲JSON負載發送到傳入的webhook。

<FONT FACE="Monospace,Courier">LPPR 051600Z 35010KT CAVOK 27/14 Q1020</FONT><BR> 

從這個例子中,我怎麼能做到這一點使用$ HTML = str_get_html和$ HTML的「找???

我設法發送完整的HTML內容,但那不是我想要的。

<?php 

include_once('simple_html_dom.php'); 
$html = file_get_html('http://test.com')->plaintext; 


// The data to send to the API 

$postData = array('text' => $html); 


// Setup cURL 
$ch = curl_init('https://uri.com/test'); 
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE, 
    CURLOPT_RETURNTRANSFER => TRUE, 
    CURLOPT_HTTPHEADER => array(
     'Authorization: '.$authToken, 
     'Content-Type: application/json' 
    ), 
    CURLOPT_POSTFIELDS => json_encode($postData) 
)); 

// Send the request 
$response = curl_exec($ch); 

// Check for errors 
if($response === FALSE){ 
    die(curl_error($ch)); 
} 

// Decode the response 
$responseData = json_decode($response, TRUE); 

// Print the date from the response 
echo $responseData['published']; 
?> 

非常感謝

回答

0

如果您確定該線是完全一樣的,你可以

$line = explode('<br>', $response); 

這將創建與<FONT>xxxxx</FONT>數組在每個位置的每一行。

從2號線僅獲取文本

$filteredResponse = strip_tags($line[1]); 
+0

這工作!謝謝! –

+0

不客氣。請接受答案。 – iliaz

0

您可以使用PHP:DOMsimple_html_dom

以下示例從谷歌的搜索鏈接的替代品。

<?php 
# Use the Curl extension to query Google and get back a page of results 
$url = "http://www.google.com"; 
$ch = curl_init(); 
$timeout = 5; 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
$html = curl_exec($ch); 
curl_close($ch); 

# Create a DOM parser object 
$dom = new DOMDocument(); 

# Parse the HTML from Google. 
# The @ before the method call suppresses any warnings that 
# loadHTML might throw because of invalid HTML in the page. 
@$dom->loadHTML($html); 

# Iterate over all the <a> tags 
foreach($dom->getElementsByTagName('font') as $link) { 
     # Show the <font> 
     echo $link->textContent; 
     echo "<br />"; 
} 
?> 

$dom->getElementsByTagName('font')替換標記,你想要的。

快樂刮

參考: http://htmlparsing.com/php.html http://php.net/manual/en/book.dom.php

+0

非常感謝!如果我用標籤'font'替換,行將如何回顯$ link-> getAttribute('href'); –

+0

'$鏈路> innertext' – Thamaraiselvam