Text Size
Sunday, May 20, 2012
Get a look down
Displaying items by tag: php

Sometimes we need to generate a CSV file dynamically, and launch it as downloadable file, it works fine in Firefox, Opera, Chrome and other guru browsers, but when we talk about Internet Explorer, maybe we need to hack the code.

By googling a little, i found an easy solution, so in php, we can do it like this :

 

1
2
3
4
5
6
7
8
9
<?php
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"exportevent.csv\";" );
header("Content-Transfer-Encoding: binary"); 
?>
Published in Code snippets

Here's a little snippet that allow's us to remove any non alphanumeric characters from strings. It would be very usefull when a developper need to format a given string from a registration form for example.

1
2
3
4
5
6
7
8
9
10
<?php
// Our string
$words = "Hello! My Name Is Nabil SADKI 007!!!";
 
// Formatted string
$formatted_words = preg_replace("[^A-Za-z0-9]", "", $words ); // This will print : HelloMyNameIsNabilSADKI007
 
// Get only alpha
$formatted_words = preg_replace("[^A-Za-z]", "", $words ); // This will print : HelloMyNameIsNabilSADKI
?>
Published in Code snippets
Here's how you can get the first N elements of an array, it's so simple with the use of array_slice :
1
2
3
4
5
6
7
8
9
10
<?php
// Array
$myArray = array("bird", "dog", "cat", "horse", "lizard");
 
// Get the 2 first elements
$output = array_slice($myArray, 0, 2);
 
// Result
// This will give an array with elements : "bird", "dog"
?>
Published in Code snippets
Usefull tricks