mysql PHP将产品从数据库导出到csv

bq3bfh9z  于 2022-10-31  发布在  Mysql
关注(0)|答案(1)|浏览(144)

当我执行下面的脚本时,我必须从数据库中导出我所有的产品到一个csv文件中,但是我不能管理把从数据库中返回所有产品的函数放在一起到一个数组或迭代器中。我的php代码放在下面。我做错了什么?谢谢。

<?php
require_once("config/db-connect.php");
function toate_produsele_active() {

$array_produse = mysqli_query($mysqli, "SELECT product_id, product_name, category_url, product_short_desc, product_price, product_photo FROM mb95_products");

while ($row = mysqli_fetch_assoc($array_produse)) {
print_r($row);
}
}

$f = fopen('php://output', 'wb');
if($f) {
foreach(toate_produsele_active() as $produs) {
    $coloane = array(
        $produs['product_id'],
        $produs['product_name'],
        $produs['category_url'],
        $produs['product_short_desc'],
        $produs['product_price'],
        implode('[,]', str_replace('[,]', '[%2C]', $produs['product_photo'])),
    );
    fputcsv($f, $coloane, ';', '"');
}
fclose($f);
}
?>

我最终想要的结果应该看起来像这样:
1;标题产品1;描述产品1;罗恩;60;5;产品图片. jpg

m2xkgtsf

m2xkgtsf1#

假设toate_produsele_active()按预期工作。我创建了三个函数,因此代码可以重用,并在代码中添加了注解:

<?php
// Create the header for the csv file (ID, Titlu, Descriere, Pret)
function getHeader()
{
    $csv = '';
    $headerData = array();
    $header = 'ID, Titlu, Descriere, Pret';
    $columns = explode(',', $header);
    foreach ($columns as $column) {
        $headerData[] = $column;
    }
    // the titles are separated by the semicolon
    $csv .= implode(';', $headerData) . "\n";

    return $csv;
}
// add the products data into an array and then fill the csv file 
// with rows. Separated by semicolon
function iterateItems($csv)
{    
    $data = [];    
    foreach (toate_produsele_active() as $produs) {
        $data[] = $produs['product_id'];
        $data[] = $produs['product_name'];
        $data[] = $produs['category_url'];
        $data[] = $produs['product_short_desc'];

        $csv .= implode(';', $data) . "\n";
    }

    return $csv;
}

function exportAll()
{
    // name and location of the file
    $csvFile = 'products.csv';

    // create the header: ID, Titlu, Descriere, Pret
    $csvHeader = getHeader();

    // add the header and then the product data into the csv file
    $csv = iterateItems($csvHeader);

    // save he file (location, file)
    file_put_contents($csvFile, $csv);
}
// call the function
exportAll();

相关问题