'in csv file data is not in proper format show some html code in cakephp

Data in csv file is not in proper format it show like as javascript code or html code in only one column

Code in userscontroller

for export data in csvfile from database of user table 
    public function export() {
            $this->response->download("export.csv");
    
            $data = $this->Users->find('all');
            $this->set(compact('data'));
    
            $this->layout = 'ajax'; 
    
            return;
        }
    
    // app/Views/Users/export
    
    header('Content-type: text/csv');
    header("Content-Disposition: attachment; filename=export.csv");  
    
    foreach ($data as $row) {
        foreach ($row['Users'] as $cell) {
            // Escape double quotation marks
            $cell = '"' . preg_replace('/"/','""',$cell) . '"';
        }
        echo implode(',', $row['Users']) . "\n";
    }

Screenshot of output:

Screenshot of output



Solution 1:[1]

As I see here, Look like it is debug variable for debug bar or something like that (cause i not have full view of your csv file) So I can suggest some action to check as i know:

  • Check "your template" file as see $this->layout = 'ajax'; . It may contain default debug bar or custom code. Empty ajax layout look like this
  • Because CSV file is not normal view. So better you just set this action not use any view layout by using $this->layout = false; or in Cake 3 use $this->viewBuilder()->layout(false);

Sometime php code also inject to output file or view page because your code have notice or warning message. So please check the full csv file, start read from where html code begin and you will understand the problem

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Long