Convert file format for DOS and Unix

Most of my development works are done on Linux/Unix. I use / evaluate a lot of open source projects and some files has ^M when edited from this platform. This is because the file was saved in dos format which uses a different EOL (end of line character).

To overcome this problem, just run this simple unix command:

$ dos2unix <filename>

Note that the original file will be overwritten. Do a ‘man’ to check options available for this command.

End Of Line

Different systems uses different EOL  characters, which also known as line break or newline.

Unix uses ‘\n’. Windows uses ‘\n\r’. Apple/Mac uses ‘\r’.

Other EOL conversion commands: unix2dos, mac2unix, unix2mac, mac2dos, dos2mac.

PHP: Current URL

'http' . ($_SERVER['HTTPS']) ? 's' : '') . ':// . 
$_SERVER['SERVER_NAME'] . 
((in_array($_SERVER['SERVER_PORT'], array(80, 443)) ? '' : ':' . $_SERVER['SERVER_PORT']) . 
'/'

$_SERVER[’HTTPS’] will be non-empty value if it’s running over SSL or using HTTPS protocol.

$_SERVER[’SERVER_PORT’] 80 is standard port and 443 is standard ssl port. The port number will be appended to the URL if not using these 2 standard ports.

PHP: Parsing XML

In PHP5, parsing and processing xml can be easily done with SimpleXML extension.

To parse xml file:

$obj = simplexml_load_file($file);

To parse xml string:

$obj = simplexml_load_string($string);

Example

<data>
    <tag>value 1<tag>
    <tag attribute="attrbute value">value 2<tag>
</data>

After loading xml into $obj, access tag values as class method:

	
$obj->tag
$obj->tag[$i] //if more than 1 tag

Access tag attribute as array:

$obj->tag['attribute']
$obj->tag[$i]['attribute'] // if more than 1 tag

JavaScript: Convert input text to upper or lower case

To convert to upper case, add onChange attribute to <input> and call toUpperCase() function:

<input type="text" onchange="javascript:this.value=this.value.toUpperCase();" />

to convert to lower case:

<input type="text" onchange="javascript:this.value=this.value.toLowerCase();" />

HTML: Definition List

I always forget the syntax for <dl>, <dt> and <dd> tags, even though it’s obvious – list, terms and definition / description.

Here’s the correct syntax:

<dl>
    <dt>the term</dt>
    <dd>description</dd>
</dl>