2013-07-26 51 views
-2

我想刮cetrain值關閉網站:http://www.gitanjalijewels.com/颳去一個網站以獲取PHP中的特定值。

我使用下面的代碼:

<?php 


$data = file_get_contents('http://www.gitanjalijewels.com/category.php?id=39'); 
$regex = '/GOLD RATES:: (.+?) ,/'; 
preg_match($regex,$data,$match); 
var_dump($match); 
echo $match[1]; 

>

但是結果我得到的是:

array(0){}

無法確定可能會出現什麼問題?任何人都可以請指導我走向正確的方向?

+3

請在百萬次使用DOM解析器。 – DevZer0

+0

PHP不是我的域名,除此之外,我無法找到任何簡單的東西,我閱讀了關於SO的最多投票答案,關於正則表達式如何搞砸事情,但我有選擇! – user2613996

+0

加上本網站不支持DOM,其原因搞砸了! – user2613996

回答

2

不要使用正則表達式解析HTML。使用DOM解析器。

include('simple_html_dom.php'); 
$html = file_get_html('http://www.gitanjalijewels.com/'); 

foreach($html->find('/html/body/div[1]/div/table/tbody/tr[3]/td/li/marquee/') as $element)          
{ 
     echo $element->plaintext . '<br>'; 
} 

輸出:

GOLD RATES::(24kt999:--Rs.2868), (24kt995:--Rs.2841), (22kt:--Rs.2675), (18kt:--Rs.2236) 
1
$regex = '/GOLD RATES::[\s]?(.+?)[\s]?,/si'; 
preg_match($regex,$data,$match); 
var_dump($match); 

輸出:

array(2) { 
    [0] => 
    string(32) "GOLD RATES::(24kt999:--Rs.2868)," 
    [1] => 
    string(19) "(24kt999:--Rs.2868)" 
} 
1
$html = file_get_contents("http://www.gitanjalijewels.com/category.php?id=39"); 

$matches = array(); 
preg_match("/GOLD RATES::[^\>]+/", $html, $matches); 
print("<pre>"); 
var_dump($matches); 
print("</pre>"); 

if(count($matches) > 0){ 
    $html = $matches[0]; 
    $matches = array(); 
    preg_match_all("/\(([^:]+)\:([^\)]+)\)/", $html, $matches); 

    $goldPrice = array(); 
    if(count($matches) > 0){ 
     for($i = 0; $i<count($matches[1]); $i++) 
      $goldPrice[ $matches[1][$i] ] = $matches[2][$i]; 
    } 
    print("<pre>"); 
    var_dump($goldPrice); 
    print("</pre>"); 
} 

result: 
array(4) { 
    ["24kt999"]=> 
     string(9) "--Rs.2868" 
    ["24kt995"]=> 
     string(9) "--Rs.2841" 
    ["22kt"]=> 
     string(9) "--Rs.2675" 
    ["18kt"]=> 
     string(9) "--Rs.2236" 
}