Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Removing <?xml version="1.0"?> from the output of XSLTProcessor->transformToXml()

Just add this as a top level element in your XSL document.

<xsl:output method="html" />


Thanks to this post on php.net for the answer:
http://us3.php.net/manual/en/xsltprocessor.transformtoxml.php#80887

Super simple XML and PHP

This is a super simple implementation of a concept found here:
http://xtech06.usefulinc.com/schedule/paper/19

This xml class provides a very simple way to open an XML file, get information from the XML file, modify information from the XML file and save the XML file. It also supports automatic creation of new XML files based on an automatically incrementing ID senerio (similar to auto incrementing primary keys in databases).

The creation of new XML files is done by looking for a "template" xml file named 0.xml in the directory passed to the create function. If the template file is found, then it is loaded into the xml class and saved to a new file whose name is one more than the highest filename (of course the xml extension is added on). Eventually, I will try and add some validation code and whatever else, but for now I'm trying to keep things simple.

This requires the DOM module to be built into PHP.
I am using PHP 5.

If anyone has any ideas on how to improve this, feel free to post comments.

<?php

class xml
{
	var $dom;
	var $uri;

	function xml($uri)
	{
		$this->dom = new DOMDocument();

		if(preg_match('/\.xml$/', $uri))
		{
			$this->uri = $uri;
		}
		else
		{
			$this->uri = $this->create($uri);
		}
		$this->dom->load($this->uri);
	}

	function set($query, $value)
	{
		$path = new DOMXPath($this->dom);
		$nodes = $path->query($query);
		$nodes->item(0)->nodeValue = $value;
	}

	function get($query)
	{
		$path = new DOMXPath($this->dom);
		$nodes = $path->query($query);
		return $nodes->item(0)->nodeValue;
	}

	function save()
	{
		$this->dom->save($this->uri);
	}

	function create($uri)
	{
		// Build the URI of the template file.
		$template = sprintf('%s/0.xml', $uri);

		// If the directory doesn't exist, we can't really
		// do anything.
		if(!is_dir($uri))
		{
			exit('No directory');
		}

		// If the template file doesn't exist, we cannot
		// create a new file automatically.
		if(!file_exists($template))
		{
			exit('No template');
		}

		// Load the template XML into our DOMDocument.
		$this->dom->load($template);

		// Scan the directory into an array.
		$dir = scandir($uri);

		// Pull out the highest ID
		$id = str_replace('.xml', '', array_pop($dir));

		// Add one to it
		$id++;

		// Construct the new path with the new ID
		$uri = sprintf('%s/%s.xml', $uri, $id);

		// Save the new file
		$this->dom->save($uri);

		// Return the URI of the new XML file.
		return $uri;
	}
}

// The following code will create a new XML file
// under the directory /var/www/data/users.
$x = new xml('/var/www/data/users');
$x->set('//user/name', 'John Doe');
$x->save();

?>

get key value using strpos

// description of your code here

foreach($check as $key=>$val) {
               if(strpos($val,$filter_value))
               {
                    $var = $key;
               }
          }

Creating tables and inserting data on database using a file

// Creating tables and inserting data on database using a file

$filename = "database.sql";

          $filesize       = filesize($filename);
          $file_position  = isset($HTTP_GET_VARS['pos']) ? $HTTP_GET_VARS['pos'] : 0;
          $errors         = isset($HTTP_GET_VARS['ignore_errors']) ? 0 : 1;

          if (!$fp = fopen($filename,'rb')) {
               echo "Unable to open file $filename";
          }
          
          $buffer = '';
          $inside_quote = 0;
          $quote_inside = '';
          $started_query = 0;

          $data_buffer = '';

          $last_char = "\n";

          // Sets file position indicator
          fseek($fp,$file_position);

          while ((!feof($fp) || strlen($buffer))) {
               do {
                    // Deals with the length of the buffer
                    if (!strlen($buffer)) {
                         $buffer .= fread ($fp,1024);
                    }

                    // Fiddle around with the buffers
                    $current_char = $buffer[0];
                    $buffer = substr($buffer, 1);


                    if ($started_query) {
                         $data_buffer .= $current_char;
                    }  elseif (preg_match("/[A-Za-z]/i",$current_char) && $last_char == "\n")  {
                         $started_query = 1;
                         $data_buffer = $current_char;
                    } else {
                         $last_char = $current_char;
                    }
               } while (!$started_query && (!feof($fp) || strlen($buffer)));


               if ($inside_quote && $current_char == $quote_inside && $last_char != '\\') {
                    // We were inside a quote but now we aren't so reset the flag and carry on
                    $inside_quote = 0;
               
               } elseif ($current_char == '\\' && $last_char == '\\')     {
                    $current_char = '';     
               
               } elseif (!$inside_quote && ($current_char == '"' || $current_char == '`' || $current_char == '\'')) {
                    // We have just entered a new quote
                    $inside_quote = 1;
                    $quote_inside = $current_char;
               
               } elseif (!$inside_quote && $current_char == ';') {

                    // edit database
                    $db_prefix = $boardname."_".$sel_domain."_phpbb_";
                    $data_buffer = str_replace("phpbb_", "$db_prefix", $data_buffer);
                    $data_buffer = str_replace("{domain}", "$sel_domain_name", $data_buffer);
                    $data_buffer = str_replace("{path}", "$sel_domain_path", $data_buffer);                         
                    $data_buffer = str_replace("{language}", "$language", $data_buffer);
                    $data_buffer = str_replace("{boardadmin}", "$boardadmin", $data_buffer);
                    $data_buffer = str_replace("{admin_pass_md5}", "$admin_pass_md5", $data_buffer);                         
                    $data_buffer = str_replace("{email}", "$email", $data_buffer);                         
                    $data_buffer = str_replace("{timing}", "$timing", $data_buffer);
                    $data_buffer = str_replace("{boardname}", "$boardname", $data_buffer);
                    $data_buffer = str_replace("{initial_forum}", "$initial_forum", $data_buffer);
                    $data_buffer = str_replace("{initial_forum_desc}", "$initial_forum_desc", $data_buffer);
                    $data_buffer = str_replace("{initial_post_subject}", "$initial_post_subject", $data_buffer);
                    $data_buffer = str_replace("{initial_post}", "$initial_post", $data_buffer);                              
               
                    // End of query so execute query, clear data buffer and advance counter
                    mysql_query($data_buffer);

                    $data_buffer = '';
                    $last_char = "\n";
                    $started_query = 0;
               }

               $last_char = $current_char;
          }


          $new_position = ftell($fp) - strlen($buffer) - strlen($data_buffer);

          fclose($fp);

Select all tables with a certain prefix in a database and remove them

// Select all tables with a certain prefix in a database and remove them

mysql_query("SHOW TABLES LIKE '[table_prefix_here]\_%'");

#Delete Data from old database
define("TABLE_PREFIX", [table_prefix]);
define("TABLE_PREFIX_LEN", strlen(TABLE_PREFIX));

$tables = array();
$r = mysql_query("SHOW TABLES");

while (($row = mysql_fetch_row($r)) !== FALSE) {
     if (TABLE_PREFIX == substr($row[0], 0, TABLE_PREFIX_LEN)) {
          $tables[] = $row[0];
          mysql_query("DROP TABLE $row[0];");
          }
     }

Fix for EE Multi-relationship field in PHP4

// http://expressionengine.com/forums/viewreply/192755/

Open your /system/modules/weblog/mod.weblog.php file and find from this line:
    
    // -------------------------------------------
    // 'weblog_entries_tagdata' hook.

to this line:
    
    //
    // -------------------------------------------

Replace between those comments with this:

    if (isset($EXT->extensions['weblog_entries_tagdata']))
    {
        // -- PHP4 Fix For call_user_func_array not passing by reference
        global $Weblog; $Weblog = $this;
        // -- End Fix
        
        $tagdata = $EXT->call_extension('weblog_entries_tagdata', $tagdata, $row, $this);
        if ($EXT->end_script === TRUE) return $tagdata;
        
        // -- PHP4 Fix For call_user_func_array not passing by reference
        $this = $Weblog; unset($Weblog);
        // -- End Fix
    

PHP will organize form values into arrays if you ask nicely

I took stole this example directly from php.net but it is worth the infraction. Name your form fields correctly and they are placed in arrays in the $_GET or $_POST arrays. This example would return something like this if you selected two of the "beer" elements.

Array
(
[personal] => Array
(
[name] => Fred Derf
[email] => fred@example.com
)

[beer] => Array
(
[0] => warthog
[1] => guinness
)

)

<?php
if ($_POST) {
    echo '<pre>';
    echo htmlspecialchars(print_r($_POST, true));
    echo '</pre>';
}
?>
<form action="" method="post">
    Name:  <input type="text" name="personal[name]" /><br />
    Email: <input type="text" name="personal[email]" /><br />
    Beer: <br />
    <select multiple name="beer[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="submit" value="submit me!" />
</form>

Installs pecl memcache php5 extension on a Joyent Accelerator

//

#!/bin/sh
# Installs pecl memcache php5 extension on a Joyent Accelerator
#
# $Id$

VERSION=2.2.3
TEMPDIR=`/usr/bin/mktemp`

cd ${TEMPDIR}
/usr/sfw/bin/wget http://pecl.php.net/get/memcache-${VERSION}.tgz
/opt/local/bin/tar -zxvf memcache-${VERSION}.tgz
cd memcache-${VERSION}
/opt/local/bin/phpize
./configure
/usr/bin/make
/usr/bin/make install
/opt/local/bin/gsed -i"" "s/;extension=memcache.so/extension=memcache.so/" /opt/local/etc/php.ini

关于MYSQL的用法

// MYSQL是一种非常常用的东西
//I JUST WANT TO TEST

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
   die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Test php mysql pdo_mysql

// description of your code here

<?php $link = mysql_connect('localhost','mydbuser','mydbpassword');
if (!$link) {
        die('Could not connect to MySQL: ' . mysql_error());
} echo 'mySql Connection OK';
mysql_close($link);

$dbh = new PDO('mysql:host=localhost;dbname=test','mydbuser','mydbpassword');
if ($dbh) {
        echo 'mysql_pdo CONNECTION OK';
}
else {echo 'mysql_pdo ERROR';}
?>