How To: PHP OAuth Twitter

So, you’re building a web based twitter client in PHP.  Easy, just use a simple Twitter API client and call the Twitter API directly.  But what if you don’t want to store the user’s Twitter authentication information anywhere?  It’s a security risk anyway and some people don’t want to give up their account details to a 3rd party.  So what to do?  The solution is to use OAuth with Twitter. Continue reading “How To: PHP OAuth Twitter”

How-To: Removing trailing whitespace from a string with php

Need to remove the trailing whitespace characters from a string in php? chomp() is how you do it in Perl, however in PHP it’s just as easy. Simply use rtrim():

// $string = "|my string with trailing whitespace  |"
$string = rtrim($string);

// $string = "|my string with trailing whitespace|"

It’s that easy! There is also the trim() function which does the same at the start of the line. You can view the manual reference here.

How-To: Read an RSS Feed with PHP

An easy way to read an RSS feed with PHP is to use the MagpieRSS library. This provides a simple API to read an RSS feed, and elegantly deal with the issues of timeouts and caching.

It’s as simple as:

require('rss_fetch.inc');
$rss = fetch_rss($url);
echo "Site: ", $rss->channel['title'], "<br>
";
foreach ($rss->items as $item ) {
	$title = $item[title];
	$url   = $item[link];
	echo "<a href=$url>$title</a></li><br>
";
}

More information is available from the MagpieRSS website

How-To: Determine Real hostname in php

If you need to know the real host name of your server using php, use the following command:

<? echo gethostbyaddr (gethostbyname ($_SERVER["SERVER_NAME"])); ?>

This will return the server’s hostname, not the address that the script is being accessed by. Very useful if you have a script that needs to run on multiple servers.

How-To: Fix SimpleXML CDATA problem in php

If you’ve used the SimpleXML functions in PHP, you may have noticed some strange things happening with CDATA values in your XML file/string. All I needed to do was extract the value of my CDATA fields, however these were always coming back blank in the structure that simplexml_load_file returns.

Finally, after hours of trawling google, I’ve come up with the following solution:

$xml = simplexml_load_file($this->filename,
'SimpleXMLElement', LIBXML_NOCDATA);

Use this line of code when you are loading the XML file into the SimpleXML Object.  The key is the LIBXML_NOCDATA option as the third parameter. This returns the XML object with all the CDATA data converted into strings. You can read about this in the php manual.

This solved all the problems I was having getting CDATA values out of SimpleXML in php. Hope it helps someone.