Categories
PHP Tips & Tutorials XML Tips and FAQ

How to delete / remove nodes in SimpleXML

The other day I was testing and playing with SimpleXML to process some XML documents when I came to a problem – I realized that I needed to delete a node before dumping the XML object to text. However if you are familiar with SimpleXML, it doesn’t come with a down right way to remove nodes like DOMDocument does.

A few searches on Google neither helped – people were just saying how simple SimpleXML was and it simply could not fulfill a task like this.

You know what I did? Yes, just ‘unset‘ the node.

$str = <<<STR
<a>
  <b>
    <c>
    </c>
  </b>
</a>
STR;

$xml = simplexml_load_string($str);
unset($xml –> a –> b –> c); // this would remove node c
echo $xml –> asXML(); // xml document string without node c

There you go!

Categories
SQL / MySQL Tips and Tutorials

Using SQL to Find records existing in one table but not in another

The 2 tables are built with an identical data structure. Say you have records spread in both tables but neither of them are complete because both contain unique records. You need to consolidate the 2 tables into one with all unique records from each table.

NOT EXISTS clause is just the way to do it in SQL. Let’s try:

SELECT * FROM table2 WHERE NOT EXISTS (SELECT * FROM table1 WHERE id = table2.id)

This will select all records from table2 that don’t exist in table1 by id. To get a complete table of unique records from both table1 and table2, you need to just insert the results here into table1.

INSERT INTO table1 (SELECT * FROM table2 WHERE NOT EXISTS (SELECT * FROM table1 WHERE id = table2.id))

Categories
PHP Tips & Tutorials

Warning: session_start(): Cannot send session cookie – headers already sent

It is known that you have to make sure nothing’s already sent to output to perform a successful http header modification. As such, in PHP, you will keep an eye on possible white spaces before the use of header() function to modify delivery headers. For example,
<?php
header('...');
?>

this tiny snippet would fail if unscrupulous white spaces were prepended before the ‘<?php’ tag.

So upon error of Warning: session_start(): Cannot send session cookie – headers already sent, you should first check if there’s additional unwanted white spaces before calling session_start().

If this didn’t work for you. The second approach definitely would.

So you are calling session_start() from an included / required file, such as:

1.php
<?php
require_once('2.php');
?>

2.php
<?php
session_start();
?>

PHP works in a way that adds unexpected characters if you are including files, to make sure the header is sent successfully you’ll have to suppress the output using output buffer control in PHP. Just add the 2 lines in 1.php and you’ll be fine:

1.php
<?php
ob_start(); // start manual output buffer control
require_once('2.php');
ob_end_clean(); // manually erase the output buffer without sending it to client
?>

That’s it! Hopefully it’s solved at your end!

Categories
Hosting Tips & Deals Linux Server Administration Tips PHP Tips & Tutorials

Cron jobs (Crontab jobs) tricks and tips on DreamHost

Crontab is a utility tool on Unix-like OS that enables you to make a program daemon scheduled to run at a specified interval. For example, to fetch news feed and import them into your own database every hour on the hour or to send pre-written newsletters at a given time everyday.

With DreamHost you can easily add Crontab jobs at their proprietary web panel, but there are 2 tricks.

With PHP, you can specify the version to run the script, PHP4 or PHP5. DreamHost has both popular php versions installed at different locations:

/*PHP4: */
/usr/local/bin/php
/*PHP5: */
/usr/local/php5/bin/php

With any PHP script, you can always achieve the same results with lynx -dump command that accesses and loads the script as any other browsers would do, thus making the server run the script.

Also it’s required to add this line:

#!/usr/local/bin/php -q

at the top before <?php declaration if you are configuring crontab in command line mode rather than adding it from the web panel of DreamHost.

Categories
Programming Tips & Insights Web Design Tips and Insights

One SSI directive to save all programming muggle’s effort and time

SSI stands for Server Side Includes that is a default module in Apache web server. In essence, it provides a very simple mechanism to include one HTML file in another one, thus tremendously reducing redundant coding and increase the ease of later maintenance.

So, to get 80% out of SSI, the only directive you pretty much need is this:

<!--#include virtual="/parts/footer.html" -->

Make sure ‘include’ is immediately after ‘#’ without any blank spaces.

As the file name suggests, you are adding a common site footer. You can do this to all other pages on your site, making updating footer very easy because you only need to modify /parts/footer.html to get the changes done.

To get 80% our of SSI, you only need one directive, that is <!–#include virtual=" … " –>. It’s the essence I believe. And to get the rest 20%, you might also want to know about these handy ones (incomplete, just examples I think that will amuse you):

Get file size:

<!--#fsize virtual="/parts/ads.html"-->

Get last modified date:

<!--#flastmod virtual="index.html"-->

Get visitor IP address:

<!--#echo var="REMOTE_ADDR" -->

Get today’s date:

<!--#echo var="DATE_LOCAL" -->

Setting and getting a variable:

<!--#set var="name" value="Rich" -->
<!--#echo var="name" -->

You can even do some concatenation:

<!--#set var="firstname" value="Rich" -->
<!--#set var="lastname" value="Mond" -->
<!--#set var="name" value="${firstname} ${lastname}" -->

You get the idea. =) However, to get SSI to work on your server, you might need to add the following directives to httpd.conf (that is, if you are your own server administrator) or .htaccess (if you are on your own by shared hosting):

Options +Includes

For further reading, please refer to:

  1. Apache SSI Tutorial
  2. Kavoir SSI Framework
  3. wikipedia SSI
  4. HTML Code Tutorial, SSI help forum is a good place to go seeking for help. I’m there by the name of yangyang. =)
Categories
JavaScript Tips & Tutorials

Differences of function.apply() and function.call() in JavaScript

Function object methods function.apply() and function.call() basically do the same job, that is to invoke the function as if it was the method of a specified object so that the ‘this’ keyword within the function is treated as that object rather than the global object.

var x = 20;
function f(s)
{
alert(this.x + s);
}
f('!');

‘this’ keyword refers to global object by default, so the code above kicks out an alert of ’20!’. However, with

var x = 20;
var o = {x:40}; // o is an object with a property of x = 40
function f(s)
{
alert(this.x + s);
}
f('!');
f.call(o, '!'); // invoking function f as a method of object o, so this.x makes out to o.x = 40 thus an alert of '40!' instead of '20!'.
f.apply(o, ['!']); // does the same thing as f.call(o, '!')

‘this’ keyword is set to object o. You get the idea. The only difference you should pay attention to is that the second parameter supplied to f.apply() is an array.

Categories
JavaScript Tips & Tutorials

DOM event detection: event bubbling and event capturing

There’s essentially 2 ways for the DOM to detect any events, namely event capturing and event bubbling.

Event capturing is a method that the browser captures the event from the top elements to the bottom where the event actually takes place. For example, the moment you click on an <img> which is the child of a <p> which is further spawned from a <div>, the document element namely <body> captures the event first before it gets down the path to the eventual source of the event, that is the <img>.

Event bubbling is just the other way around where the event propagation actually goes inside out. Picture the sound waves travelling in air. With an <img> inside a <p> which is inside a <div>, a click on the image would first be seen and processed from the original target first, then the <p>, and the <div>, finally the document element at the root.

events bubbling and events capturing

Internet Explorer doesn’t have an implementation of event capturing, so events triggered in it can only travel from bottom to the top, a.k.a the bubbling way.

Categories
JavaScript Tips & Tutorials

Stop / Disable JavaScript Error Warnings

Use the following line to keep the browser or console from warning the user of your program errors.

window.onerror = function( ) { return true; }

That’s it! 🙂

Categories
JavaScript Tips & Tutorials

JavaScript: Changing Browser Window Width / Height

This petite JavaScript snippet defines several functions in the namespace of Geometry that will come handy when you need to manipulate window geometry, freeing you from the depressing chores of distinguishing different browsers for their distinct implementations of virtually the same features.

/**
 * This module defines functions for querying window and document geometry.
 *
 * Geometry.getWindowX/Y( ): return the position of the window on the screen
 * Geometry.getViewportWidth/Height( ): return the size of the browser viewport area
 * Geometry.getDocumentWidth/Height( ): return the size of the document
 * Geometry.getHorizontalScroll( ): return the position of the horizontal scrollbar
 * Geometry.getVerticalScroll( ): return the position of the vertical scrollbar
 *
 * Note that there is no portable way to query the overall size of the
 * browser window, so there are no getWindowWidth/Height( ) functions.
 *
 * IMPORTANT: This module must be included in the <body> of a document
 *            instead of the <head> of the document.
 */

var Geometry = {};

if (window.screenLeft) { // IE and others
    Geometry.getWindowX = function( ) { return window.screenLeft; };
    Geometry.getWindowY = function( ) { return window.screenTop; };
}
else if (window.screenX) { // Firefox and others
    Geometry.getWindowX = function( ) { return window.screenX; };
    Geometry.getWindowY = function( ) { return window.screenY; };
}

if (window.innerWidth) { // All browsers but IE
    Geometry.getViewportWidth = function( ) { return window.innerWidth; };
    Geometry.getViewportHeight = function( ) { return window.innerHeight; };
    Geometry.getHorizontalScroll = function( ) { return window.pageXOffset; };
    Geometry.getVerticalScroll = function( ) { return window.pageYOffset; };
}
else if (document.documentElement && document.documentElement.clientWidth) {
    // These functions are for IE 6 when there is a DOCTYPE
    Geometry.getViewportWidth =
        function( ) { return document.documentElement.clientWidth; };
    Geometry.getViewportHeight =
        function( ) { return document.documentElement.clientHeight; };
    Geometry.getHorizontalScroll =
        function( ) { return document.documentElement.scrollLeft; };
    Geometry.getVerticalScroll =
        function( ) { return document.documentElement.scrollTop; };
}
else if (document.body.clientWidth) {
    // These are for IE4, IE5, and IE6 without a DOCTYPE
    Geometry.getViewportWidth =
        function( ) { return document.body.clientWidth; };
    Geometry.getViewportHeight =
        function( ) { return document.body.clientHeight; };
    Geometry.getHorizontalScroll =
        function( ) { return document.body.scrollLeft; };
    Geometry.getVerticalScroll =
        function( ) { return document.body.scrollTop; };
}

// These functions return the size of the document. They are not window
// related, but they are useful to have here anyway.
if (document.documentElement && document.documentElemnet.scrollWidth) {
    Geometry.getDocumentWidth =
        function( ) { return document.documentElement.scrollWidth; };
    Geometry.getDocumentHeight =
        function( ) { return document.documentElement.scrollHeight; };
}
else if (document.body.scrollWidth) {
    Geometry.getDocumentWidth =
        function( ) { return document.body.scrollWidth; };
    Geometry.getDocumentHeight =
        function( ) { return document.body.scrollHeight; };
}
Categories
Free PHP Classes & Library PHP Tips & Tutorials

What is PHP framework & Who are the Best PHP Frameworks?

Basically, PHP frameworks are programming layers that are promoted above PHP itself and that are much easier and quicker to deploy, normalizing and packaging 80% of the routines one is expected to work on without them, such as database interfaces. Therefore they free you from the chores of coding from very scratch line by line and do the common tasks that are shared among most of the projects for you.

Like many other frameworks, PHP frameworks such as the Code Igniter and CakePHP are built upon the MVC model. MVC stands for Model, View and Controller.

Model is essentially a prototype of all similar entities bearing shared descriptive properties. In the database, a table can almost always be interpreted as a model.

View prescribes how the data(models) are presented(in the browser, as webpages for example). In most cases, a view is a webpage template.

Controller is the control hub that can be directly manipulated to control other stuff, namely models and views. It’s where the logic lies in your PHP applications.

3 major PHP frameworks:

1. Code Igniter, is well documented and has a shorter learning curve, thus more appealing to beginners.
2. CakePHP, is more of cup of tea for veteran PHP developers. As intuitive to use as CI, but not as well documented and the learning curve might be a little too long.
3. Smarty, I don’t know much about this one and only tried it once. It’s more like a templating system than a framework, I think. If you don’t plan to add registration functionalities, session management and things like that, you can go with Smarty, though CI and cake can also do a good job in templating.

Update: There’s also a 4th greatly renowned php framework that is Zend Framework. All seems well done and I’m gonna try it out for one of my recent projects soon.