Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The simplest solution I can think of:</p> <pre><code>// The filename to write to $csvFile = 'theCSVfile.csv'; $csvRows = array(); foreach ($collection as $product_all) { $sku = $product_all['sku']; $product_id = Mage::getModel('catalog/product')-&gt;getIdBySku($sku); $product = Mage::getModel('catalog/product'); $product -&gt;load($product_id); // Replacing quotation marks with CSV escaped ones $name = str_replace( '"' , '""' , $product['name'] ); $csvRows[] = "{$sku},\"{$name}\""; } file_put_contents( $csvFile , implode( "\n" , $csvRows ) ); </code></pre> <p>Bear in mind that this may produce invalid CSV syntax if the <code>$name</code> variable contains commas or other unusual characters.</p> <p>As noted by <strong>Bogdan</strong>, this may be memory intensive, as it involves holding all of the rows in RAM before performing a single write to the file. If that is a concern, or you are dealing with a very large number of rows, the following code batches the writes into smaller chunks.</p> <pre><code>// The filename to write to $csvFile = 'theCSVfile.csv'; // Rows per chunk $csvChunk = 1000; // Initialise the Array $csvRows = array(); // Variable to check if first write performed $firstWriteDone = false; function writeChunk(){ global $csvFile, $csvRows, $csvChunk, $firstWriteDone; if( count( $csvRows )==$csvChunk ){ // Chunk Limit Reached - Write to disk file_put_contents( $csvFile , ( !$firstWriteDone ? "\n" : '' ) . implode( "\n" , $csvRows ) , ( !$firstWriteDone ? FILE_APPEND : 0 ) ); // Set the First Write Done flag $firstWriteDone = true; // Reset the Array $csvRows = array(); } } foreach ($collection as $product_all) { $sku = $product_all['sku']; $product_id = Mage::getModel('catalog/product')-&gt;getIdBySku($sku); $product = Mage::getModel('catalog/product'); $product -&gt;load($product_id); // Replacing quotation marks with CSV escaped ones $name = str_replace( '"' , '""' , $product['name'] ); $csvRows[] = "{$sku},\"{$name}\""; if( count( $csvRows )==$csvChunk ){ // Chunk Limit Reached - Write to disk writeChunk(); } } if( count( $csvRows ) ){ // Write the Last Chunk, even if not at the limit writeChunk(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload