2016-03-15 41 views
1

我想抓取產品的sku,正則表達式不按預期工作

請幫我寫這個正則表達式。

這裏是我的代碼 -

$url = "http://api.findify.io/v1.0/store/search?callback=jQuery111206735094679573879_1458022087824&q=154701001&key=5b31ee91-78fa-48e1-9338-1748ca55028e&analytics%5Bkey%5D=5b31ee91-78fa-48e1-9338-1748ca55028e&analytics%5Bvisit%5D=true&analytics%5Buniq%5D=true&analytics%5Burl%5D=http%253A%252F%252Fwww.pandorasoem.com%252Fsearch%2523q%253D154637401&analytics%5Bbaseurl%5D=http%253A%252F%252Fwww.pandorasoem.com%252Fsearch%2523q%253D154637401&analytics%5Bhost%5D=www.pandorasoem.com&analytics%5Bwidth%5D=1920&analytics%5Bheight%5D=1200&analytics%5Binner_width%5D=1438&analytics%5Binner_height%5D=667&analytics%5Bdoc_width%5D=1438&analytics%5Bdoc_height%5D=915&analytics%5Bscroll_x%5D=0&analytics%5Bscroll_y%5D=0&analytics%5Bvisit_id%5D=Ts22zuHHGJRZc3U1&analytics%5Buniq_id%5D=BoeCUKSzgdML6C50&byPage=24&page=0&_=1458022087825"; 
$ch1= curl_init(); 
curl_setopt ($ch1, CURLOPT_URL, $url); 
curl_setopt($ch1, CURLOPT_HEADER, 0); 
curl_setopt($ch1,CURLOPT_VERBOSE,1); 
curl_setopt($ch1, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)'); 
curl_setopt ($ch1, CURLOPT_REFERER,'http://www.google.com'); //just a fake referer 
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch1,CURLOPT_POST,0); 
//curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 20); 
$htmlContent= curl_exec($ch1); 
curl_close($ch1); 
preg_match_all('/["\']?totalHits["\']?\s*:\s*(\d+)/i', $htmlContent, $count); 
print_r($count);  

preg_match_all('/"sku".*:.*"(.*)".*/i', $htmlContent, $sku); 
print_r($sku); 

它顯示擷取SKU空白陣列。它適用於Totalhits。

Update URL

+1

列表您'sku'的響應是一個數組(雖然你的'totalHits'確實是一個數字,在這種情況下是3),請使用'JSON'解析器而不是正則表達式。 – Jan

+0

@Jan我不知道如何使用JSON解析器。你能舉個例子嗎 – Steve

+0

無論如何,這是一個'jQuery'響應,所以在這裏:http://api.jquery.com/jquery.getjson/ – Jan

回答

1

單從URL中移除的回調參數,它會返回正確的JSON,那麼你就可以JSON轉換爲數組或對象,做任何你想要

從刪除callback=jQuery111206735094679573879_1458022087824&的URL

到JSON轉換爲數組使用json_decodehttp://php.net/manual/en/function.json-decode.php

等你拿$htmlContent後,你可以用$jsonData = json_decode($htmlContent,true);

轉換可以print_r JSON來檢查它的鍵/值,

,或者如果你想獲得的sku -s

$skus = Array(); 
foreach($jsonData['data']['hits'] as $hit) { 
    $skus[] = $hit['sku']; 
} 
+0

你能給我一個詳細的例子。我不熟悉JSON .. – Steve

+0

試圖解釋一下 – ogres

+0

Json是空的..我沒有得到任何東西后print_r($ jsonData),也使用foreach代碼。也試圖打印$ skus。那麼它顯示'PHP警告:爲foreach()提供的無效參數' – Steve

相關問題