Archive for the ‘PHP’ Category

Converting CSV to JSON with PHP

Wednesday, October 16th, 2013

JSON is a little bit more verbose then csv (comma seperated values), but widely used nowadays on the net, because it format is somewhat like a literal Javascript object. Now Javascript and PHP have native JSON support it is a very good and handy format to exchange data, much less verbose then XML and easier to create and parse on the client.

How easy?

In PHP:

 json_encode ($array);
 json_decode($json);

In Javascript:


JSON.stringify(myObject)
JSON.parse(myJson)


But csv is also still widely used:
  • myslq dump
  • spreadsheet
To concert CSV to JSON in PHP is actually quite simple:
$file="mysqlTable.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
print json_encode($array);

The first two lines are simple, and do not need any explaining.

Convert CSV into an array

The third line, converts the csv file into a multidimensional array

$array = array_map("str_getcsv", explode("\n", $csv));

Explode the csv string on `line ends` into an array of lines, and convert the lines themselves with the safe native function  `str_getcsv` to an array. Although it is tempting to parse a line of csv with

explode(",", $line);

always use the native functions for csv like, str_getcsv.

Convert an array into JSON

Once you have the $array, simply convert it to JSON:

print json_encode($array,JSON_PRETTY_PRINT);

JSON_PRETTY_PRINT is optional and will print the JSON with whitespace.

Use it for debugging, don’t use it in production, it will add extra whitespace and thus size to your output.

Create JSON/Ajax server response

header('Content-Type: application/json');

print json_encode($array);

Turns your server into Ajax serving JSON.

Using the new upcoming Netbeans 7.3 HTML5

Wednesday, November 7th, 2012

The new version 7.3 of Netbeans will offer improved support for Javascript/HTML5 apps. It looks really promising: a lot of code completion, documentation that is available during editing, and a build-in PHP server.

If you edit JavaScript a lot you know what “use strict” means. It’s a pragma that will let the program you use the new ECMAScript 5 `strict mode`. ECMAScript is the official standard of JavaScript.

To turn into `strict mode` just start your script with “use strict”. Or type it as the first rule in a function, to use strict mode only in that function,
Strict mode will protect you, among other things, to accidentally declare a variable in the global scope.

function(){
text = "just temporary text used in this function"
}

Will define a global variable text, which is a bad thing, you forgot to write :

function(){
var text = "just temporary text used in this function"
}

Strict mode protects you from making these kind of mistakes, it will warn you, this code won’t run:

function(){
"use strict";
text = "just temporary text used in this function"
}

To add this useful command to the code snippets in Netbeans.
Go to Tools -> Options -> Editor -> Code Templates and add new
Abbrevation: us
Expanded Text: “use strict”;

Now you can type `us` hit TAB and voila: “use strict”; is added in your JavaScript file.

Tips for using the Netbeans editor for Kohana and Kostache / Mustache templates using `surround with`

Monday, May 14th, 2012

A nice feature of NetBeans is the support for `code templates`: abbreviations that expand into snippets of code when the TAB key is pressed after typing the a shortcut in the editor.

You can type fn TAB and have it expand to

function blabla () {

}

That’s very convenient for long and often needed code phrases.

`Surround with` code templates

Another very useful feature is the `surround with` code snippet. It isn’t very well documented on the Netbeans PHP pages, well more or less not at all, but you can add your own snippets for `surround with` too.

If your using Mustache templates with the Kohana framework, you will find the next snippet extremely useful, when you’re updating your templates multilingual. Mustache templates are very clean and elegant template files that work with a myriad of languages like PHP, Python and Javascript. Also they escape code automatically, so I really can recommend them. No more logic in the HTML template files, well just the most basic.

For example you have this Mustache template:

<h2>Recipes</h2>
<ul>
{{#recipes}}
	<li>{{name}}</li>
{{/recipes}}
</ul>

To make it multilingual for use with Kostache we have to change it to:

<h2>{{#__}}Recipes{{/__}}</h2>

To do that in Netbeans add this to the code templates: tools -> options -> editor -> tab `Code templates` -> new

It doesn’t matter what you choose for abbreviation, because were not gonna use it as code completion with shortcut TAB, but surround with is triggered with SHIFT ENTER.

Choose something like translation, then paste this:

{{#__}}${selection allowSurround}{{/__}}


Now go back to your template, select Recipes, and press SHIFT ENTER or click the yellow light-bulb. That will offer the extra command `surround with` your snippet.

Not documented on the Netbeans PHP wiki, but extremely useful.

The needed PHP function in your view class:

public function __() {
return array('i18n', 'get');
 }

Fix broken UTF8 encoded RSS feeds in php

Friday, July 3rd, 2009

Parsing feeds with the SimpleXML object is a walk in the park. But it can turn into a pain in the ass, when the provided XML feed isn’t correctly UTF8 encoded and I can tell you, there are some ugly ones out there in the wild.

Parsing RSS feeds with SimpleXML

Normally you can load and parse a feed as simple as:

<?
$feed = simplexml_load_file(rss.xml);

foreach ($feed->channel->item as $item){ ?>
  <h3><?= $item->title ?></h3>
  <p><?= $item->description ?></p>
<? } ?>

That’s a standard. Sometimes though the XML is not proper UTF8 encoded, and the following nasty error occurs loading in into the SimpleXML object.

Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 6: parser error : Input is not proper UTF-8, indicate encoding ! Bytes: 0xEB 0x6C 0x65 0x20 in index.php on line 33

How to fix this

First I tried to filter out the bad characters with str_replace, but that’s silly. I didn’t feel right. So I looked further and I stumbled on this quite unknow function iconv.

What’s the iconv module

This module contains an interface to iconv character set conversion facility. With this module, you can turn a string represented by a local character set into the one represented by another character set, which may be the Unicode character set. Supported character sets depend on the iconv implementation of your system.

The iconv function is available since PHP 4.0.5

Description

string iconv ( string $in_charset , string $out_charset , string $str )

Performs a character set conversion on the string str from in_charset to out_charset .

A better and safer way of parsing

To be on the safe side, never read in a feed directly into a SimpleXML object, but do it this way:

$feed = file_get_contents($feed_url);

$feed = iconv("UTF-8","UTF-8//IGNORE",$feed);

$feed = simplexml_load_string($feed); 

There is another reason to do this. Reading in a feed with file_get_contents is much faster then loading it straight into a SimpleXML object , at least in PHP < 5.2x. So following above instructions you will experience a performance gain and get rid of some nasty unexpected errors.

Dating takes time, women are difficult but PHP?

Wednesday, March 18th, 2009

One of the big annoyances is having a blog or webpage in a certain language and that all the dates appear on your website in English. Of course you can choose just numbered formats, but sometimes the month or the day of the week in words adds that needed little extra polish.

Formatting a date in PHP

Normally a date is formatted like this with the date() function:

[sourcecode language=”php”]
< ?= date(‘d-m-Y’) ?>
[/sourcecode]

Formatting a localised date in PHP

But to format a date in your preferred language you need to use the strftime function:

Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

So we also need the setlocale() function. This function let you set the language to use for the formatting. Your system or server should have them installed, otherwise it’s not possible! And most of them are not installed by default, although easily available.
What does the setlocale() function do:

Returns the new current locale, or FALSE if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid.
An invalid category name also causes a warning message. Category/locale names can be found in RFC 1766 and ISO 639. Different systems have different naming schemes for locales.

Tough pages to consume to be honest, but let’s go on.

Locales settings on your server

You can find the installed localisations in this file on a Linux server:

[sourcecode language=”xml”]
vi var/lib/locales/supported.d/local
[/sourcecode]

My server only had one line by default!
Simply add the one’s you’re missing. You can find all possible localisations in this file:

[sourcecode language=”xml”]
/usr/share/i18n/SUPPORTED
[/sourcecode]

Don’t add them all: it will decrease performance.

So we’re nearly done:

[sourcecode language=”php”]
< ?
setlocale(LC_TIME,’nl-NL.UTF-8′);
echo strftime(‘%s-$b-%y’,time())
?>
[/sourcecode]

You need to enter the correct encoding aswell, otherwise it won’t work. This is dependent of the server settings, so it will influence the portability of your code a bit.
Above code will give you the current date in Dutch, but we need another function to create localised dates from stored timestamps of the MySQL database.

Converting stored Timestamps to PHP understandable format

A MySQL timestamp value won’t work as a direct input to the strftime function. We need to convert it with another function: strtotime.

So we end up with something like this:

[sourcecode language=”php”]
< ?
setlocale(LC_TIME,’nl-NL.UTF-8′);
echo strftime(‘%A %d $b %y’,strtotime($row->timestamp))
?>
[/sourcecode]

Quite a long road to take for a boring date!

Your are browsing
the Archives of My Beloved PHP in the 'PHP' Category.
Categories
Archives
Links