2017-04-26 79 views
1

我試圖瞭解如何刮從PHP的黃頁網站解碼電話號碼&捲曲。使用PHP和捲曲刮解碼信息

下面是一個例子網址: https://www.gelbeseiten.de/test

通常情況下,你可以在技術上與像這樣做:

$ch = curl_init(); 
$page = curl_exec($ch); 

if(preg_match('#example html code (.*) example html code#', $page, $match)) 
    $result = $match[1]; 
    echo $result; 

但是你上面提到的頁面上無法直接找到在HTML中的電話號碼碼。必須有辦法獲得電話號碼。

你能幫我嗎?

最好的問候,

詹妮弗

+1

這可能是更容易使用'DOMDocument'和'XPath' - cntaining的電話號碼元素得心應手分配類('phone'),所以你可以訪問他們直接,而不是試圖使用正則表達式 – RamRaider

+0

@RamRaider電話號碼是以某種方式編碼,然後附加到HTML DOM中,我認爲OP詢問什麼,所以它不是關於使用正則表達式或DOMDocument ...等 – hassan

+0

[網站刮'使用PHP] ://stackoverflow.com/questions/26397335/website-scraping-using-php) – LuFFy

回答

0

Don't use regex to parse html,使用HTML解析器像DOMDocument,即:

$html = file_get_contents("https://www.gelbeseiten.de/test"); 
libxml_use_internal_errors(true); 
$dom = new DOMDocument(); 
$dom->loadHTML($html); 
$xpath = new DOMXPath($dom); 

foreach ($xpath->query('//span[contains(@class,"nummer")]') as $item) { 
    print trim($item->textContent); 
} 

輸出:

(0211) 4 08 05(0211) 4 08 05(0211) 4 08 05(0211) 4 08 05(0231) 9 79 76(0231)... 
+0

謝謝,但是這個腳本沒有得到數字的最後兩位數字。 – user1219432

+0

這個網站有一個保護,只顯示電話號碼的最後一部分,如果啓用JavaScript,這是不是用PHP的情況。您可能想要使用www.seleniumhq.org/。 –

0

正如評論建議 - 使用一個XPath表達式產生電話號碼根據需要。

$url='https://www.gelbeseiten.de/test'; 

$dom=new DOMDocument; 
$dom->loadHTMLFile($url); 
$xp=new DOMXpath($dom); 

$query='//li[@class="phone"]'; 
$col=$xp->query($query); 

if($col){ 
    foreach($col as $node)echo $node->nodeValue . "<br />"; 
} 
$dom = $xp = $col = null; 
+0

謝謝,不幸的是,這個腳本沒有得到數字的最後兩位數字。你有一個想法,如何解決這個問題? – user1219432