Archive for the 'PHP' Category

23rd Jan 2009

Expanding All Tree Nodes

I am working on a project that requires the data provider for a tree component to be reloaded periodically. When I would reload the data, the tree would revert to it’s collapsed state. From a usability point of view, this was not the best of situations. So I started doing some research how to expand all of the nodes in a tree. I came across of a couple of places using loops such as:

private function expandTree():void{
for (var i:int = 0; i < thisTree.dataProvider.length; i ++){
thisTree.expandChildrenOf(thisTree.dataProvider[i], true)
}
}
private function collapseTree():void{
for (var i:int = 0; i < thisTree.dataProvider.length; i ++){
thisTree.expandChildrenOf(thisTree.dataProvider[i], false)
}
}

When looking at this, I noticed the name of the function is expandChildrenOf, which to me inferred it would expand all of the children of the given node. So I looked into a bit further and the description for this function in the documentation states (http://livedocs.adobe.com/flex/2/langref/mx/controls/Tree.html#expandChildrenOf()):

expandChildrenOf () method
public function expandChildrenOf(item:Object, open:Boolean):void

Opens or closes all the tree items below the specified item.
Parameters
item:Object — the starting item

open:Boolean — toggles an open or close operation

So if that is the case and I pass this function the root node of the dataProvider such as in the following:

this.myTree.expandChildrenOf(this.myTree.dataProvider[0],true);

It did as expected and expanded all of the nodes under the root node. No loop required.

Posted by Posted by Jeremy Wischusen under Filed under ActionScript 3, DHTML, Flex, PHP Comments 1 Comment »

29th Jun 2008

Upon Reflection

The other day I was revising the one of the systems on one of the sites I work on into an object oriented structure. Everything was all well and good until I realized that I had to pass the values contained in one of my new objects into the templating system that we use. So I initially just passed a reference to the object. This did not work out so well.

It turns out that the templating system was having a hard time dealing with instance variables that are references to other objects and decided to throw a fit and halt processing. So I started looking for an easy way to translate my object into something the templating system could use (an array). More specifically, I wanted to produce an array that contained the values of my instance variables, but only the ones that were not references to other objects.

I decided to add a method called toArray to the object in question. Now I just needed an implementation. My first shot at this was to use PHP’s get_object_vars passing $this as a parameter.

public function toArray(){
return get_object_vars($this);
}

However, all was not well. It seems that when you call this function passing $this as a parameter it returned all of the variables from all of the objects referenced in instance variables. So I was basically back were I started.

So I gave it a bit of thought and came up with this.

/**

* Convert values held in instance variables into an array.
* This allows the data to be more easily used by a
* smarty variable  as well as making the data more easily cachable.
*
* @return Array
*/
public function toArray ()
{
$data = array();
foreach ( $this as $key => $var )
{
/**
* Exclude complex objects from the array.
*/
if ( !get_class( $var ) )
{
$data[$key] = $var;
}
}
return $data;
}

Problem solved. Now I only got back an array that contained the values of instance variables for that specific class that were not references to other objects.

Posted by Posted by Jeremy Wischusen under Filed under OOP, PHP Comments No Comments »

03rd Jun 2008

PHP http_build_query

I was browsing through
PHP Cookbook : Solutions and Examples for PHP Programmers by David Sklar, Adam Trachtenberg the other day and while looking through the section on making REST calls, i noticed this function:

http_build_query

I have been doing PHP for some time and this was the first time I had ever seen it. I asked one of my co-workers this morning about it and he had never heard of it either. Here is what it does:

string http_build_query ( array $formdata [, string $numeric_prefix [, string $arg_separator ]] )

Generates a URL-encoded query string from the associative (or indexed) array provided.

So in other words, instead of manually building a query string like:

$url = ‘http://www.somedomain.com/somepage.php?firstname=’.$firstName.’&lastname=’.$lastname;

You can do something like this:

$queryString = http_build_query(array(‘firstname’=>$firstname, ‘lastname’=>$lastName));
$url = ‘http://www.somedomain.com/somepage.php?’.$queryString;

This could be especially useful for long query strings so you don’t have to type out all of the string concatenation. It you would like to learn more about this method go here.

Posted by Posted by Jeremy Wischusen under Filed under PHP Comments No Comments »

30th May 2008

YouTube API Video Upload

For my latest project I had to work with the new YouTube API. Let us just say the documentation could be improved. It is not that the information is not there, but there is a lack of cross referencing and if you jump to a particular sample, there seems to be the assumption that you have read other parts of the documentation and sometimes they refer to relevant sections, sometimes they do not. And some things are just left out entirely.

For example, the PHP API documentation shows you how to generate the file browse form, but does not mention (aside from a comment in the code about white space in the keywords) the restrictions on the inputs for the form that you would have to submit prior to getting to this point. Some of these include:

  • The < and > characters will cause an error if included in any of the inputs.
  • Submitting a single character keyword will cause an error.
  • The category select form items must have certain values, you can not simply submit the actual text representation of the category.
  • Description is limited to 5000 characters.
  • Total keyword string length can not exceed 120 characters and a single key word can not be over 25 characters.

These can be found elsewhere in the documentation, but again a link to relevant information in the actual PHP example could have saved me a lot of searching and time.

That being said, we did finally get it working (I think).

Posted by Posted by Jeremy Wischusen under Filed under PHP Comments 1 Comment »

16th Apr 2008

Sending XML DATA via the POST Method in PHP using CURL

One of the projects I worked on involved sending XML formated data to a remote server via the post method. To do this, we ended up using the PHP CURL extension. You will need this installed on your server for this example to work. You can find installation instructions here.

Sending Page:

The sending page is where we implement our CURL code:

<?php

/*Create a DOMDocument object to build the XML*/
$dom = new DOMDocument();
$dom->formatOutput = TRUE;
$root = $dom->appendChild($dom->createElement(‘request’));
$root->setAttribute(‘clientId’, ‘123’);
$root->setAttribute(‘clientKey’, ’32IFJ23OFIJIWR’);
$root->setAttribute(‘type’, ‘MESSAGE’);
$message = $root->appendChild($dom->createElement(‘message’));
$recipient = $message->appendChild($dom->createElement(‘recipient’));
$type = $recipient->appendChild($dom->createElement(‘type’, 5));
$id = $recipient->appendChild($dom->createElement(‘id’, ‘+16505551212’));
$text = $message->appendChild($dom->createElement(‘text’, ‘Yeah we can send XML’));
$sendXML = $dom->saveXML();

/*Initialize CURL. CURL works in a similar fashion to SESSION in that you have to initialize it and then close it */

/*Initialize CURL and pass it the URL of the page we are sending the data to*/
$curl =curl_init(‘http://localhost/dev/gateway.php’);

/*Set CURL Options. See this page for a description of the option constants.*/

/*In this case we are sending XML, so set the header type to XML*/
curl_setopt ($curl, CURLOPT_HTTPHEADER, Array(“Content-Type:text/xml”));
curl_setopt($curl,CURL_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $sendXML); // post the xml
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // set timeout in seconds
$xmlResponse = curl_exec ($curl);
curl_close ($curl);

/*Since we set the CURL_RETURNTRANSFER to a value that evaluates to true, the returned response from the page we sent the request to will be printed to the page*/
?>

The Receiving Page:

This example is incredibly simple since all I am trying to demonstrate is the communication of XML POST data between pages/servers. However, since the data is there on the recieving page, you can do with it as you like before returning a response. In this case, all we do is echo back out the passed XML.

<?php
header(‘content-type: text/xml’);

/*Because we passed the XML directly to curl_setopt($curl, CURLOPT_POSTFIELDS, $sendXML) in the sending page, we use HTTP_RAW_POST_DATA’ to access it. If we had done something like curl_setopt($curl, CURLOPT_POSTFIELDS, array (‘xmldata’=>$sendXML) ) , then we would access it via $_POST[‘xmldata’]*/

echo $GLOBALS[‘HTTP_RAW_POST_DATA’];
?>

Result:

The result of this process is the following:

<?xml version="1.0"?>
<request clientId="123" clientKey="32IFJ23OFIJIWR" type="MESSAGE">
  <message>
    <recipient>
      <type>5</type>
      <id>+16505551212</id>
    </recipient>
    <text>Yeah we can send XML</text>
  </message>
</request>

While this example is essentially a round about way of of echoing the XML that was built on the sending page, it is enough to demonstrate the concept of passing XML data via a post request. What you do with the data on the reciving page and what you return is entirely up to you and will depend on what you are trying to accomplish.

Posted by Posted by Jeremy Wischusen under Filed under PHP Comments No Comments »

15th Apr 2008

Using PHP’s DomDocument to Generate XML from an SQL Query

One of my side projects (well many of them now that I think of it) requires me to load data from a database on server into Flash. Back in the old days. and with simple data, I might have done something like:

echo ‘name=’.$name.’&email=’.$email;

… and so on and then load that string into a Flash LoadVars object, on in AS 3 a URLVariables via a URRequest.
This is ok for small simple data, but not so much for large amounts of data requiring a complicated string concatination.

Then one day it dawned on me that you can use the PHP DomDocument object to create a well formatted XML document and skip the whole string concatenation altogether. Furthermore, Flash makes loading external XML from a URL a very simple thing. Hence I could skip the whole LoadVars experience as well.

After doing this once or twice, I also realized that you could pretty much automate the whole process of generating the XML document inside the while loop for fetching the database rows. Essentially what I end up with is an XML document with tag names that match the column names of the table I am performing the query on with the node values matching the value for that row of the query.

Below is a sample of this and the output it produces with some of the more sensitive details removed:

PHP:

<?php
header (“content-type: text/xml”);

/*Create a DomDocument Object*/

$dom = new DomDocument(‘1.0’);
$dom->formatOutput = true;

/*Create a root element for the XML document*/

$root = $dom->createElement(‘stores’);

$dom->appendChild($root);
mysql_connect(‘localhost’,’username’,’password’) or die(‘Could not connect to db server’);
mysql_select_db(‘database_name’) or die(‘Could not select DB’);

$sql = ‘SELECT * FROM table_name’;

$call = mysql_query($sql);
while($row = mysql_fetch_assoc($call)){
/*For each row returned, create a node to represent that row*/

$store = $dom->createElement(‘store’);
$root->appendChild($store);

/*Loop through the returned row and create a node that matches the column name and use the value for the node’s value*/

foreach($row as $key=>$val){
$col = $dom->createElement($key,stripslashes($val));
$store->appendChild($col);
}
}
/*echo out the XML to the page*/

echo $dom->saveXML();
?>

Output (edited for sensitive data, but representative) :

<stores>
<store>
<companyName>Diamond Imports</companyName>
<companyDesc>
Diamond Imports is one of Australia’s largest diamond importers specializing in loose diamonds, certified diamonds, wholesale diamonds, excellent cut diamonds and ideal cut diamonds. Diamond Imports is 100% Australian owned and operated company based in Sydney.
</companyDesc>
<companyAddress>Bridge Street</companyAddress>
<suburb>Sydney</suburb>
<city>Sydney</city>
<state>NSW</state>
<AverageRatingGuarantee>5</AverageRatingGuarantee>
<AverageRatingSelection>5</AverageRatingSelection>
<AverageRatingHours>5</AverageRatingHours>
<AverageRatingService>5</AverageRatingService>
<AverageRatingAmbience>5</AverageRatingAmbience>
<AverageRatingCertification>5</AverageRatingCertification>
<AverageRatingKnowledge>5</AverageRatingKnowledge>
<AverageRatingImpression>5</AverageRatingImpression>
</store>
</stores>

To load this into flash or flex, all I do is point to the URL of the page that generates the XML:

var storeData:XML = new XML();

storeData.ignoreWhite = true;

storeData.load(“getStores.php”);

Posted by Posted by Jeremy Wischusen under Filed under Flash, PHP Comments 2 Comments »