2017-09-14 116 views
0

如何將抓取的數據導出爲.csv文件?我使用PHP簡單的HTML DOM解析數據。下面是代碼:使用php和簡單的html dom將數據導出爲CSV文件

foreach ($linkoviStranica as $stranica) 
{ 
    $podaciStranice = "http://someurl/$stranica"; 

    $data = file_get_html($podaciStranice); 


    $name = $data->find('div[class="price-card-name-header-name"]'); 
    $onlinePrice = $data->find('div[class="price-box online"]'); 
    $diffPrice = $data->find('div[class="price-box paper"]'); 

    echo "<strong>".$name[0]->innertext."<strong>"."<br>"; 
     if (!empty($onlinePrice[0]->innertext)) 
     { 
     echo $onlinePrice[0]->innertext."<br>"; 
     } 
    if (!empty($diffPrice[0]->innertext)) 
    { 
     echo $diffPrice[0]->innertext."<br>"; 

     echo "---------------------"."<br>"; 

    } 
} 

我要出口,$名稱,$ onlinePrice,$ diffPrice到CSV文件與頭的格式如下:

name onlinePrice diffPrice 
example 10   44 
xxxx  412  461 
zzzzz  1414   41 

你能幫幫我嗎?謝謝!

回答

1

事情是這樣的:

// Define a array to hold all the data 
$data = []; 

// OR use this line if you want the headers with names on the first line of the file 
// $data = [['name', 'onlinePrice', 'diffPrice']]; 

// Loop the raw data 
foreach ($linkoviStranica as $stranica) { 
    $podaciStranice = "http://someurl/$stranica"; 
    $data = file_get_html($podaciStranice); 

    $name = $data->find('div[class="price-card-name-header-name"]'); 
    $onlinePrice = $data->find('div[class="price-box online"]'); 
    $diffPrice = $data->find('div[class="price-box paper"]'); 

    // Add current row to out array 
    $data[] = [ 
     $name[0]->innertext, 
     $onlinePrice[0]->innertext, 
     $diffPrice[0]->innertext 
    ]; 
} 

// Open a new file. Replace the file name with the name you'd like 
$fp = fopen('file.csv', 'w'); 

// Loop each row in the data array 
foreach ($data as $fields) { 
    // This method converts a row to a CSV line (http://php.net/manual/en/function.fputcsv.php) 
    fputcsv($fp, $fields); 
} 

// Close the file handler 
fclose($fp); 
+0

TNX這就是我一直在尋找,有小的變化,我已經加上了首本:fputcsv($ FP,陣列( '名','在線價格','差價'));因爲data ['name','online price','diff price']給我一個錯誤。 – dilesko

+0

@dilesko查看我的代碼片段中的第四行。它添加了這個頭文件。如果它解決了你的問題,請接受我的答案,以便以後人們更容易找到答案。 – OptimusCrime

0
$header ="SNo , Order Date , Order Number , Compaign , Amount , Order Status , Used Date , Cancel Reason , Order Commision , Payment Date , Payment Status \n"; 
      $header1 =$header ; 
$result=''; 
foreach ($data as $fields) { 
    $result= 'echo your data with coma seprated '."\n"; 
} 
$all=$header.$result; 
$name="report.csv"; 
header("Content-type: application/csv"); 
header("Content-Disposition: attachment; filename=".$name); 
header("Pragma: no-cache"); 
header("Expires: 0"); 
print "$header1 $result";