2013-03-28 27 views
0

请不要关闭这个问题,我知道有很多已经购买的解决方案似乎都没有工作,或者至少不是为我工作。我从谷歌联盟网络产品饲料csv文件,它在zip,.txt(csv)制表符分隔符。我到目前为止已经unziped文件和读取文件,但我想要做的是将该数据转储到MySQL数据库,第一行的csv是标题,我想根据csv文件创建字段名称,并将数据分别放在数据库中,一些csv文件中的字段为空。我也希望能够再次运行它(可能我会为此运行cron作业),并在其中插入新数据。我的csv文件的 例如:CSV到MYsql与PHP

ProductID ProductName ProductURL BuyURL ImageURL Category CategoryID PFXCategory BriefDesc ShortDesc IntermDesc LongDesc ProductKeyword Brand Manufacturer ManfID ManufacturerModel UPC Platform MediaTypeDesc MerchandiseType Price SalePrice VariableCommission SubFeedID InStock Inventory RemoveDate RewPoints PartnerSpecific ShipAvail ShipCost ShippingIsAbsolut ShippingWeight ShipNeeds ShipPromoText ProductPromoText DailySpecialsInd GiftBoxing GiftWrapping GiftMessaging ProductContainerName CrossSellRef AltImagePrompt AltImageURL AgeRangeMin AgeRangeMax ISBN Title Publisher Author Genre Media Material PermuColor PermuSize PermuWeight PermuItemPrice PermuSalePrice PermuInventorySta Permutation PermutationSKU BaseProductID Option1 Option2 Option3 Option4 Option5 Option6 Option7 Option8 Option9 Option10 Option11 Option12 Option13 Option14 Option15 Option16 Option17 Option18 Option19 Option20  
4181615950845mkTWIN~TWIN Brylanehome Jasmine Quilt Set (Sea Green,Twin) http://gan.doubleclick.net/gan_click?lid=41000613802463546&pid=4181615950845mkTWIN~TWIN&adurl=http%3A%2F%2Fwww.brylanehome.com%2FProduct.aspx%3FPfId%3D20653%26ProductTypeId%3D2%26affiliate_id%3D017%26mr%3AtrackingCode%3D8C875316-BB51-E211-9A4A-90E2BA0278A8%26mr%3AreferralID%3DNA&usg=AFHzDLtiRj_wSyAQFEPxMBFVo4HjTeHMVA&pubid=21000000000568460 http://gan.doubleclick.net/gan_click?lid=41000613802463546&pid=4181615950845mkTWIN~TWIN&adurl=http%3A%2F%2Fwww.brylanehome.com%2FProduct.aspx%3FPfId%3D20653%26ProductTypeId%3D2%26affiliate_id%3D017%26mr%3AtrackingCode%3D8C875316-BB51-E211-9A4A-90E2BA0278A8%26mr%3AreferralID%3DNA&usg=AFHzDLtiRj_wSyAQFEPxMBFVo4HjTeHMVA&pubid=21000000000568460 http://media.redcatsecom.com/brylanehome/mc/1595_41816_mc_0845.jpg?wid=230&hei=331&qlt=95&op_sharpen=1 Bedding > Quilts   Picture perfect on any bed, this pieced and stitched quilt set is the ideal choice for spring bedding.   • A BrylaneHome® Exclusive!  • all-over floral print quilt reverses to a stripe • scalloped edges • 100% cotton   Picture perfect on any bed, this pieced and stitched quilt set is the ideal choice for spring bedding.   • A BrylaneHome® Exclusive!  • all-over floral print quilt reverses to a stripe • scalloped edges • 100% cotton face/cotton/poly fill • available in 3 sizes: Twin 2-Pc. Set 68" x 90", Full/Queen 3-Pc. 86" x 86", and King 3-Pc. 100" x 90" • machine wash/dry • imported • pair this quilt with any of our colorful and elegant sheets to create a dynamic layered look • and shop our selection of total bed sets to reinvent your décor overnight   This vibrant quilt set includes: 1 quilt and 2 standard shams (1 with twin).    Why Buy?  Our customers agree that our patchwork bedding shows off their vibrant and fun décors while offering them incredible comfort at great values.   BrylaneHome Brylane Home  4181615950845mkTWIN~TWIN    new 114.99 59.99   in stock 47                   adult   Brylanehome Jasmine Quilt Set (Sea Green,Twin)      SEA GREEN TWIN                       Home & Garden > Linens & Bedding > Bedding > Quilts & Quilt Sets 4181615950845mkTWIN~TWIN  1595-41816 

脚本我用来解压缩:

<?php 
$zip = new ZipArchive;  
    $res = $zip->open('K9349.zip'); 
    if ($res === TRUE) { 
    $zip->extractTo('extracted/'); 
    $zip->close(); 
    echo 'Unzip was successful'; 
    } else { 
    echo 'Unzip was not successful'; 
} 
?> 

下面是我想没有任何运气两个脚本。 脚本1:

<?php 
$row = 1; 
if (($handle = fopen("extracted/K9349.txt", "r")) !== FALSE) { 
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 
     $num = count($data); 
     echo "<p> $num fields in line $row: <br /></p>\n"; 
     $row++; 
     for ($c=0; $c < $num; $c++) { 
      echo $data[$c] . "<br />\n"; 
     } 
    } 
    fclose($handle); 
} 
?> 

脚本2:

<?php 

$host = '****'; 
$user = '****'; 
$pass = '****'; 
$database = '****'; 

$db = mysql_connect($host, $user, $pass); 
mysql_query("use $database", $db); 

/********************************************************************************/ 
// Parameters: filename.csv table_name 
$file = 'extracted/K9349.txt'; 
$argv = $_SERVER[argv]; 

if($argv[1]) { $file = $argv[1]; } 
else { 
    echo "Please provide a file name\n"; exit; 
} 
if($argv[2]) { $table = $argv[2]; } 
else { 
    $table = pathinfo($file); 
    $table = $table['filename']; 
} 

/********************************************************************************/ 
// Get the first row to create the column headings 

$fp = fopen($file, 'r'); 
$frow = fgetcsv($fp); 

$ccount = 0; 
foreach($frow as $column) { 
    $ccount++; 
    if($columns) $columns .= ', '; 
    $columns .= "$column varchar(250)"; 
} 

$create = "create table if not exists $table ($columns);"; 
mysql_query($create, $db); 

/********************************************************************************/ 
// Import the data into the newly created table. 

$file = $_SERVER['PWD'].'/'.$file; 
$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines"; 
mysql_query($q, $db); 

?> 

我会真的很感谢,如果你可以提供帮助。

+1

如果您的CSV文件是制表符分隔的,为什么在脚本1中使用','作为分隔符。尝试使用'while(($ data = fgetcsv($ handle,1000,“\ t”))!== FALSE) 。 – user1190992

+0

脚本1没有用,我已经做了它只是有趣的输出,即使它不好笑我怎么能发送这个数据到数据库表。这里输出[script1](http://www.lostknowledge.org/google/readcsv.php)它只是没有正确读取它,因为在csv文件中有六个thoudans记录。这里是[script2](http://www.lostknowledge.org/google/savedata.php)的输出,这里是csv [file](http://www.lostknowledge.org/google/extracted/K9349.txt) –

回答

0

请尝试下面的脚本。希望能帮助到你。

<?php 
ini_set('auto_detect_line_endings', true); 
$dbconn = mysqli_connect("host", "username", "password", "database"); 
$importedCSVFile = "filename.csv"; 
$row_data = array(); 
if(($handle = fopen($importedCSVFile, "r")) !== FALSE) { 
    $rowCounter = 0; 
    while(($row_data = fgetcsv($handle, 0, "\t")) !== FALSE) { 
     if(0 == $rowCounter) { 
      $create_query = "CREATE TABLE IF NOT EXISTS table_name ("; 
      foreach($row_data as $column) { 
       $create_query .= $column." VARCHAR(250), "; 
      } 
      $create_query = rtrim($create_query, ",").")"; 
      mysqli_query($dbconn, $create_query); 
     } 
     else { 
      $q_string = ""; 
      foreach($row_data as $key => $value) { 
       $q_string = '"'.$value.'",'; 
      } 
      mysqli_query($dbconn, 'INSERT INTO table_name VALUES ('.rtrim($q_string, ",").')'); 
     } 
     $rowCounter++; 
    } 
    fclose($handle); 
} 
?> 
+0

[点击这里查看错误](http://www.lostknowledge.org/google/onemore.php)ok这里有错误错误一:Warning:mysqli_connect()[function.mysqli-connect]:(HY000/2005 ):未知的MySQL服务器主机'localhost:/tmp/mysql5.sock'(1)在/homepages/15/d412900185/htdocs/lostknowledge.org/google/onemore.php在第3行,然后错误的每一个记录,我猜警告: mysqli_query()期望参数1为mysqli,布尔在第15行给出的/homepages/15/d412900185/htdocs/lostknowledge.org/google/onemore.php –

+0

我试图用mysql更改mysqli,它会解决连接问题,但其余的维生素也一样 –

0

来自Google会员网络产品Feed的您的csv文件可能始终采用相同的格式。所以手动创建表格可能会更简单,然后只需使用cron作业导入文件即可。