Development

/Development

Parsing XML in PHP

I’m sure many php users have needed to read some xml data into a php program and looked around hoping to find a function that can parse an XML file with a few lines of code. The road to simple XML usage may not be that short, but we’ll explore some techniques to get the data you want from an xml source. First define some xml: $contents = ‘ <rss version=”2.0″> <channel> <item> <title>Orange Cat</title> <link>http://www.phpprogrammer.co.uk/</link> <description>A nice tabby.</description> </item> <item> <title>Black Cat</title> <link>http://www.phpprogrammer.co.uk/</link> <description>A shy cat.</description> </item> </channel> </rss> ‘; Then parse the XML with this PHP code: $parser = xml_parser_create(‘UTF-8’); $did_parse = xml_parse_into_struct($parser, trim($contents), $xml_values); if(!$did_parse) { echo xml_error_string(xml_get_error_code($parser)) . " error on line: " . xml_get_current_line_number($parser); } The above example takes an “XML document”, in the form of a string, and parses it into an array ($xml_values). The array style and structure is complicated, but we will go through some simple steps to rearrange it into a usable format. $parser is an object. Functions like xml_parse_into_struct($parser … ) take $parser as an argument. […]

By | December 7th, 2011|PHP, PHP, PHP Articles, PHP Tutorials|Comments Off on Parsing XML in PHP

Simplifying PHP string reading with sscanf()

In this article we’ll see how to use sscanf() to read or parse a string in a customized way. You may have heard of the scan series of functions before, especially in other types of programming. In c based console applications that could read user input and then print text results, scan was the opposite of print. That only has a little bit to do with the function we will be talking about here. sscanf() isn’t something you will use every day. You could try to pick apart strings with other standard string functions, or use variations on preg_match() or preg_replace(). Regardless there are situations where any of these methods might be best. The first example of sscanf will be pretty simple; $scanned_float = 0.0; sscanf("9.64", "%f", $scanned_float); echo $scanned_float; You may have guessed that $scanned_float now equals 9.64. The first parameter is the string to be read. The second is a format string based on the format used by the printf() function. Any additional arguments will be filled with values computed from the function, in order. In this case the format means 1 float value. There is one variable to receive it, $scanned_float. $scanned_float = 0.0; sscanf("height: 9.64", "%f", $scanned_float); echo $scanned_float; […]

By | December 6th, 2011|PHP, PHP, PHP Articles|Comments Off on Simplifying PHP string reading with sscanf()

HTML Character Codes in PHP

PHP is a language that is highly associated with outputting HTML so that the output is shown properly in a browser. If you send the browser text with no context and no concerns for whether it is in HTML format the results are problematic and hard to predict. To format text into HTML there are many conversions that may be needed. A simple example would be converting newlines to <br /> tags. There is a well know PHP function for that of course, nl2br(). If your text uses < somewhere it also needs to be converted since HTML browsers would think it is the start of a tag. &lt; is the correct representation of < in HTML. echo htmlspecialchars(‘In "real" math, 5 < 5.1’); […]

By | December 6th, 2011|PHP, PHP, PHP Articles|Comments Off on HTML Character Codes in PHP

String Comparison in PHP – When are strings equal

It’s simple enough to check if strings are exactly equal in PHP, just use ==, the standard comparison operator. However, this assumes we are only using strings or string type variables. It is a case sensitive comparison only. In this short article we are going to go though some alternate string comparison options and learn what they are good for. First is exact type comparison, === $str1 = "100DollarsCash"; if($str1 == 100) { echo "it equals 100. "; } if($str1 === 100) { echo "it is 100. "; } […]

By | December 6th, 2011|PHP, PHP, PHP Articles|Comments Off on String Comparison in PHP – When are strings equal

PHP Sessions – Let’s Start from the Beginning

You don’t need to know about cookies (though we have an article on cookies here) to get through this article or to use sessions. Just keep in mind that they usually automatically use and set cookies, and like cookies you have to do certain things before the first output is sent (including doctype, <html>, or any whitspace). The main thing you need to do is start a session before output is started. Also, for those familiar with it, output buffering can help give you more flexibility with where session_start() or setcookie() are used. session_start(); […]

By | December 6th, 2011|PHP, PHP, PHP Articles|Comments Off on PHP Sessions – Let’s Start from the Beginning

Cookies – PHP can help with cookies

Cookies are a long standing method of storing information so it can be used again on a per user basis. Prior to database and server based sessions becoming popular cookies saw use in more complex ways. There are still a component of sessions and used on most web sites, from shopping carts to web mail. In PHP it isn’t hard to get started with cookies. setcookie("UserInfo", "3644 Alder St", time() + 3600, "/~phppro/", "iodigitalsec.com"); That example shows an example of setting the cookie UserInfo to a street address. […]

By | December 6th, 2011|PHP, PHP, PHP Articles, PHP Tutorials|Comments Off on Cookies – PHP can help with cookies

Custom Sort Functions – Organizing PHP Arrays

First I am going to demonstrate the use of the php function usort(), and then show an example of how to organize your sorting features. There isn’t much to know about the function but it’s good to practice using it since sorting functions can get pretty complex when needed. //A function must be defined and it must have 2 arguments function sort_by_suffix($a, $b){ $ax = intval(substr($a, 5)); $bx = intval(substr($b, 5)); if ($ax == $bx) return 0; elseif($a < $b) return -1; else return 1; } //an array of made up codes with a suffix at the end of each one $codes = array("G45G-5", "G15G-2", "G11G-1", "G33G-3"); //usort modifies the array rather than returning it. usort($codes, sort_by_suffix); That was an example of sorting by a portion of a string. Whatever part of the string after 5 characters that could be made into a number was used as a sortable value. If it couldn’t find sortable values the order would be unpredictable. If the suffixes were all the same it would also be that way. […]

By | October 8th, 2011|PHP, PHP, PHP Articles|Comments Off on Custom Sort Functions – Organizing PHP Arrays

PHP Regular Expression Techniques – Part 2: Characters

Now we turn to a component of regular expressions that cannot be left out. We will be dealing with characters, how to use them, and how to escape them when needed. Regular expressions are explained in the PHP manual, and in this article we are focusing on the type that are Perl compatible, like in the function preg_match. The pattern is the regular expression we are using in each case. Since it uses a slash at the beginning and end, here’s the first thing to understand about characters in patterns: each character has a meaning or function, and escaping the character gives it a different meaning. preg_replace("/catalog/toys/", "catalog/fun", "http://shop.com/catalog/toys"); //this basically cannot work because of the 2nd slash preg_replace("/catalog/toys/", "catalog/fun", "http://shop.com/catalog/toys"); //this is correct Escaping a character, as shown, is usually butting the backslash character before it. It is also normal to put it in front of a double quote or another backslash in a PHP string like that anyway, but in patterns we use it for a various things. preg_replace("/[rn]/", "", "http://shop.com/catalog/toysn"); //removes the newline r and n are also standard php string characters representing newlines. (There may be different systems for newlines from different operating systems and programs, some use n only, some use rn.) The [] brackets in the pattern mean you want to match any character inside the brackets. The function basically means replace r or n with “”. If you wanted to actually match brackets instead of that you can escape them too: [] […]

By | October 8th, 2011|PHP, PHP, PHP Articles, PHP Tutorials|Comments Off on PHP Regular Expression Techniques – Part 2: Characters

Tips for OOP Programming with PHP- Part 2: Object Storage

Before starting this article/tutorial you should already be familiar with PHP, and basic class and object syntax. This article is going to go through some useful operations you can do with objects. The first thing I want to demonstrate is how to store objects and their member variables. class MyCart{ var $items; function add_item ($artnr, $num){ $this->items[$artnr] += $num; } } session_start(); $_SESSION[‘user_cart’] = new MyCart(); In this case we are storing the object in the session variable. It is a fairly painless process, and getting that stored object on the next page the user loads is just as easy, after session_start() it will be available just like a session variable. If you try to use the session stored object on a page that does not have the class’s declaration, class MyCart{}, you will get a generic object with no member functions, as explained on the PHP manual page ‘Object Serialization’. $user_cart = new MyCart(); $user_cart_string_data = serialize($user_cart); $fp = fopen(‘data.txt’, ‘w’); fwrite($fp, $user_cart_string_data); fclose($fp); This is another basic method of storing objects. We converted the object to a string representation, and made or overwrote a file with that data. If it is not already clear, you restore the object by reading the file into a string, then using unserialize on it, reversing the effects of serialize. Like the session type of storage, you need the class to be defined in any file that uses that type of object. […]

By | October 8th, 2011|PHP, PHP, PHP Articles, PHP Tutorials|Comments Off on Tips for OOP Programming with PHP- Part 2: Object Storage

PHP Regular Expression Techniques – Part 1: Pattern Modifiers

This article will focus on PHP’s regular expression functions with pattern modifiers. Specifically these functions are of the preg type, and have preg as the prefix. preg_match() is probably the most basic regular expression function of that type and some examples of it will be used in this article. Regular expressions provide versatile ways of searching text or ‘matching’ it. A string called a pattern is used, similar to a search phrase, and in this case the patterns take a form that is basically the same a the expressions in the Perl language. […]

By | October 4th, 2011|PHP, PHP, PHP Articles, PHP Tutorials|Comments Off on PHP Regular Expression Techniques – Part 1: Pattern Modifiers

Tips for OOP Programming with PHP- Part 1: Objects and References

Programming in PHP utilizing objects is not complex and the syntax and other basics are well covered in various articles and tutorials. It’s also covered in the PHP manual and I will include a brief example for those who need a refresher. Before that I am going to illustrate the basic principals of references without using objects at all. I will then build upon that example to show how use objects and references in your program in useful and efficient ways. […]

By | October 3rd, 2011|PHP, PHP, PHP Articles, PHP Tutorials|Comments Off on Tips for OOP Programming with PHP- Part 1: Objects and References