drhdjp97757 2017-09-14 12:27
浏览 26

使用php和简单的html dom将数据导出到CSV文件

How to export grabbed data to .csv file? I'm using php simple html dom to parse data. Here is the code:

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>";

     }
 }

I want to export, $name, $onlinePrice, $diffPrice to csv file with header in the following format:

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

Could you please help me? Thanks!

  • 写回答

2条回答 默认 最新

  • doukong1901 2017-09-14 12:30
    关注

    Something like this:

    // 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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题