1

I want to export the phone numbers in .txt format line by line. Table name is customers and the column name is customer_contact_numbers from the database saiautocare I am using the Laravel framework, JQuery and MySQL database.

enter image description here

When I click that button it will ask me where to save the file and export the numbers line by line into the text file.

Here's the code:

      <div class="col-sm-6 col-lg-3">
    <div class="card text-white bg-primary">
      <div class="card-body pb-0">
        <div class="btn-group float-right">
          <button type="button" class="btn btn-transparent dropdown-toggle p-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <i class="icon-settings"></i>
          </button>
          <div class="dropdown-menu dropdown-menu-right">
            <a class="dropdown-item" href="#">Export to TXT</a>
          </div>
        </div>
        <h4 class="mb-0">{{ $TotalCustomers }}</h4> 
        <p>Marketing Numbers</p>
      </div>
      <div class="chart-wrapper px-3" style="height:70px;">
        <canvas id="card-chart1" class="chart" height="70"></canvas>
      </div>
    </div>
  </div>

I'm new to PHP and MySQL, that's why I'm sorry if I am not able to provide all the required information.

1 Answers1

2
$customers = Customer::all();
$phoneNumbers = "Phone numbers \n";
foreach ($customers as  $customer) {
  $content .= $customer->customer_contact_numbers;
  $content .= "\n";
}

// file name to download
$fileName = "contact_numbers.txt";

// make a response, with the content, a 200 response code and the headers
return Response::make($content, 200, [
  'Content-type' => 'text/plain', 
  'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
  'Content-Length' => sizeof($content)
];);
lmboom
  • 189
  • 4
  • One more question, should I add a new PHP file and add it into href "#". Then paste that code into the newly created PHP file. Is there any way I can do it without creating a new page? – Zeeshan Toor Jun 11 '20 at 11:07
  • you just need to put this code to your controller and set some routing to it and past this route into href. After users click on it it will call your controller method and starts downloading a txt file – lmboom Jun 11 '20 at 11:30
  • I will be very thankful brother if you elaborate more. I have used this GitHub project: https://github.com/AshutoshChoubey/SaiAutoCare I am new to PHP, sorry if it's bothering you :) – Zeeshan Toor Jun 15 '20 at 09:50