Export to Excel error - repeat same column on this script

67 Views Asked by At

what is wrong on my script, export goes well but repeat the first column on all results fields. I dont want to download the file, just save it and its alright until here. Header sabe OK, but line keep the same on all 30 results. what I am doing wrong?

<?php
/**
* Created by PhpStorm.
* User: leafar
* Date: 11/12/17
* Time: 09:48 PM
*/

namespace App\Action;


use Interop\Container\ContainerInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
//use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Stratigility\MiddlewareInterface;

class ExportAction implements MiddlewareInterface{

private $dbAdapter;

public function __construct(AdapterInterface $adapter) {
    $this->dbAdapter = $adapter;
}


public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{


    $sql     = new Sql($this->dbAdapter);

    $select = $sql->select(['a'=>'wp_posts']);
    $select->columns(['ID','post_content','post_title','post_name']);
    $select->where(function(Where $where){
        $where->equalTo('post_type','product');
        $where->equalTo('post_status','publish');
    });

    $select->limit(30);

    $prep = $sql->prepareStatementForSqlObject($select);
    $exec = $prep->execute();

    $ii = 0;

    foreach ($exec as $row):


        $dataExport[$ii]['post_title']   = $row['post_title'];
        $dataExport[$ii]['post_name']    = $row['post_name'];
        $dataExport[$ii]['post_content'] = $row['post_content'];

        $postid = $row['ID'];

        $sql2 = new Sql($this->dbAdapter);
        $select2 = $sql2->select(['b'=>'wp_postmeta']);
        $select2->where(function(Where $where) use($postid){
            $where->equalTo('post_id',$postid);
        });
        $prep2 = $sql2->prepareStatementForSqlObject($select2);
        $exec2 = $prep2->execute();

        foreach ($exec2 as $row2):
            if ($row2['meta_key'] == '_price'){
                $dataExport[$ii]['post_price'] = $row2['meta_value'];
            }
        endforeach;

    $ii++;
    endforeach;


    $columns = [
        '"Título do produto"',
        '"Nome do produto"',
        '"Preço com promoção"',
        '"Preço de venda em reais"',
        '"Descrição simplificada"',
        '"HTML da descrição completa"',
        '"Endereço da imagem principal do produto"'
    ];

    $headers = '';
    $line    = '';
    $data    = '';

    for($i=0;$i<=count($columns)-1;$i++){
        $headers .= $columns[$i] . "\t";
    }

    @unlink(TMP_PATH.'test.xls');

    $fp = fopen(TMP_PATH.'test.xls',"a+");
    fwrite($fp,$headers);
    fclose($fp);

    for($a=0;$a<=count($dataExport);$a++){

        $fp = fopen(TMP_PATH.'test.xls',"a+");

        $line .=  (empty($dataExport[$a]['post_title']))   ? "\t" :  '"' . $dataExport[$a]['post_title']   . '"' . "\t";
        $line .=  (empty($dataExport[$a]['post_name']))    ? "\t" :  '"' . $dataExport[$a]['post_name']    . '"' . "\t";
        $line .=  (empty($dataExport[$a]['post_price']))   ? "\t" :  '"' . $dataExport[$a]['post_price']   . '"' . "\t";
        $line .=  (empty($dataExport[$a]['post_price']))   ? "\t" :  '"' . $dataExport[$a]['post_price']   . '"' . "\t";
        $line .=  (empty($dataExport[$a]['post_name']))    ? "\t" :  '"' . $dataExport[$a]['post_name']    . '"' . "\t";
        $line .=  (empty($dataExport[$a]['post_content'])) ? "\t" :  '"' . $dataExport[$a]['post_content'] . '"' . "\t";
        $line .=   "\t";

        fwrite($fp, str_replace("\r","",trim($line)."\n"));
        fclose($fp);

    }


    echo "OK!";

    return $response->withStatus(200);


  }
}

I try a lot of different ways to write the line to file xls. But always the same result. The loop goes well if u print $dataExport[$a]['post_title'] will show all title but when I write the $line variable it repeat the first result.

1

There are 1 best solutions below

0
On

Just got it, the probem was on concatenate variable, I write it without concatenate and goes well. and change variable $headers = $headers."\n".

for($a=0;$a<=count($dataExport)-1;$a++){

        $fp = fopen(TMP_PATH.'test.xls',"a+");

        $line =
            '"' . $dataExport[$a]['post_title']   . '"' . "\t" .
            '"' . $dataExport[$a]['post_name']   . '"' . "\t" .
            '"' . $dataExport[$a]['post_price']   . '"' . "\t" .
            '"' . $dataExport[$a]['post_price']   . '"' . "\t" .
            '"' . $dataExport[$a]['post_name']   . '"' . "\t" .
            '"' . $dataExport[$a]['post_content']   . '"' . "\t" .
            '""' . "\t";

        fwrite($fp, str_replace("\r","",trim($line)."\n"));
        fclose($fp);
        unset($line);

    }