gong gong - 1 year ago 62
PHP Question

php generate data from foreach loop on txt file with table formatted

I had tried to generate txt file from php foreach loop,

it's work but the result is not parallel like if used table here :

My expectation like this :

this is my code :

$output[] = ''."\n".'';
$output[] = ' No '.' Name Product '.' Total '."\n".'';
foreach($query->result() as $row){
$results = $row->id_product;
$product = $this->db->query("select product_name from master_product WHERE product_id='".$results."'");
$product_name = $product->row()->product_name;
$output[] = ' '.$no.str_repeat(" ",20).''. $product_name.str_repeat(" ",20).''.$row->quantity.' '.$row->scale."\n".'';
file_put_contents(APPPATH."txt/test.txt", $output);

please someone help me


Answer Source

Why don't you implement a function like this:

function padColumnText($text, $colWidth)
    if (strlen($text) > $colWidth)
        return substr($text, 0, $colWidth);
    return $text . str_repeat(" ", $colWidth - strlen($text));

Then, any time you want to print a column, do it like this:

output[] = padColumnText($no, 5) . padColumnText($product_name, 20) ...

I'm assuming you want this printed to some kind of plain text file with a fixed width font. If you're doing something for the web, this is the wrong approach (you should use HTML for your formatting).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download