将MySQL数据导出到Excel

I have been looking for ways to export my data to an Excel spreadsheet. I have tried loads of examples and have been unsuccessful. This is my current code that returns, "Query Failed!". when changing the "ORDER BY" however, the spreadsheet returns the data but loops an error underneath. This is the code ive found and am using:

$con = mysql_connect($hostname,$username,$password,$db_name) or die('Could not connect: ' . mysql_error());

  function cleanData(&$str)
    {
      $str = preg_replace("/\t/", "\\t", $str);
      $str = preg_replace("/?
/", "\
", $str);

      if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
    }

    $filename = "website_data_" . date('Ymd') . ".xls";

    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-type: application/vnd.ms-excel; charset=UTF-16LE");

    $flag = false;
    $result = mysql_query("SELECT * FROM test ORDER BY field") or die('Query failed!');

    while(false !== ($row = mysql_fetch_assoc($result))) 
      {
        if(!$flag) 
          {
            echo implode("\t", array_keys($row)) . "
";
            $flag = true;
          }

        array_walk($row, 'cleanData');
        echo implode("\t", array_values($row)) . "
";
     }

Can anyone tell me why this happens? (The same thing happens using mysqli functions too)