More Books
PHP 5 Unleashed
PHP 5 Unleashed
Table of Contents
Copyright
Lead Author
Contributing Authors
Acknowledgments
We Want to Hear from You!
Reader Services
Introduction
Organization of the Book
Part I. Working with PHP for General Web Development
Chapter 1. Basic PHP Development
How PHP Scripts Work
Basic PHP Syntax
Basic PHP Data Types
Variable Manipulation
Control Structures
User-Defined Functions
Dynamic Variables and Functions
Multiple File PHP Scripts
References
Strings in PHP
Comparing Strings
Advanced String Comparison
Search and Replacement
Formatting Strings
Strings and Locales
Formatting Date and Time Values
Summary
Chapter 2. Arrays
Basic Arrays
Implementing Arrays
More Array Materials
Chapter 3. Regular Expressions
The Basics of Regular Expressions
Limitations of the Basic Syntax
POSIX Regular Expressions
Perl-Compatible Regular Expressions (PCRE)
PCRE Modifiers
A Few Final Words
Chapter 4. Working with Forms in PHP
HTML Forms 101
Working with Form Submissions in PHP
Summary
Chapter 5. Advanced Form Techniques
Data Manipulation and Conversion
Form Data Integrity
Form Processing
Summary
Chapter 6. Persistent Data Using Sessions and Cookies
HTTP Cookies
PHP Sessions
Advanced Sessions
Summary
Chapter 7. Using Templates
The What and Why of Templates
The Smarty Template Engine
Summary
Part II. Advanced Web Development
Chapter 8. PEAR
What Is PEAR?
Getting and Installing PEAR
Using the PEAR Package Manager
Using the PEAR Website
Using PEAR Packages in Applications
Summary
Reference
Chapter 9. XSLT and Other XML Concerns
Relating XML to HTML
Using XSLT to Describe HTML Output Using XML Input
PHP4 and XSLT Using the DOM XML Module
PHP4 and XSLT Using the XSLT Module
PHP5 and XSLT
Accessing XML Data Using SimpleXML
Generating XML Documents Using PHP
Summary
References
Chapter 10. Debugging and Optimizations
Debugging Your PHP Scripts
Optimizing Your PHP Scripts
Summary
Chapter 11. User Authentication
Authenticating Users in PHP
Securing PHP Code
Summary
Chapter 12. Data Encryption
Shared Secret Versus Public Key
Shared Secret Algorithms
Public Key Cryptography
Using Public Keys in PHP
Summary
Chapter 13. Object-Oriented Programming in PHP
Why Objects?
Creating Basic Classes
Advanced Classes
Special Methods
Class Autoloading
Object Serialization
Exceptions
Iterators
Summary
Chapter 14. Error Handling
The PHP Error-Handling Model
What to Do About Errors
The Default Error Handler
Error Suppression
Custom Error Handlers
Causing Errors
Putting It All Together
Summary
Chapter 15. Working with HTML/XHTML Using Tidy
Introduction
Basic Tidy Usage
Tidy Configuration Options
Using the Tidy Parser
Applications of Tidy
Summary
Chapter 16. Writing Email in PHP
The MIME Protocol
Implementing MIME Email in PHP
Summary
Part III. Building Applications in PHP
Chapter 17. Using PHP for Console Scripting
Core CLI Differences
Working with PHP CLI
CLI Tools and Extensions
Summary
Chapter 18. SOAP and PHP
What Are Web Services?
Installation
Creating Web Services
Consuming Web Services
Looking for Web Services
Summary
Chapter 19. Building WAP-Enabled Websites
What Is WAP?
System Requirements
Introduction to WML
Serving WAP Content
Sample Applications
Summary
Part IV. I/O, System Calls, and PHP
Chapter 20. Working with the File System
Working with Files in PHP
File Permissions
File Access Support Functions
Summary
Chapter 21. Network I/O
DNS/Reverse DNS Lookups
Socket Programming
Network Helper Functions
Summary
Chapter 22. Accessing the Underlying OS from PHP
Introduction
Unix-Specific OS Functionality
Platform-Independent System Functions
A Brief Note About Security
Summary
Part V. Working with Data in PHP
Chapter 23. Introduction to Databases
Using the MySQL Client
Basic MySQL Usage
Summary
Chapter 24. Using MySQL with PHP
Performing Queries from PHP
A MySQLi Session Handler
What Is a Custom Session Handler?
Summary
Chapter 25. Using SQLite with PHP
What Makes SQLite Unique?
Basic SQLite Functionality
Working with PHP UDFs in SQLite
Odds and Ends
Summary
Chapter 26. PHP's dba Functions
Preparations and Settings
Creating a File-Based Database
Writing Data
Reading Data
Sample Application
Conclusion
Part VI. Graphical Output with PHP
Chapter 27. Working with Images
Basic Image Creation Using GD
Using the PHP/GD Drawing Functions
Working with Colors and Brushes
Using Fonts and Printing Strings
General Image Manipulation
Other Graphics Functions
Summary
Chapter 28. Printable Document Generation
A Note Regarding the Examples in This Chapter
Generating Dynamic RTF Documents
Generating Dynamic PDF Documents
Related Resources
Part VII. Appendixes
Appendix A. Installing PHP5 and MySQL
Installing PHP5
Installing MySQL and PHP Modules
Installing PEAR
Appendix B. HTTP Reference
What Is HTTP?
PHP Programming Libraries for HTTP Work
Understanding an HTTP Transaction
HTTP Client Methods
What Comes Back: Server Response Codes
HTTP Headers
Encoding
Identifying Clients and Servers
The "Referer"
Fetching Content from an HTTP Source
Media Types
Cookies: Preserving State and a Tasty Treat
Security and Authorization
Client-Side Caching of HTTP Content
Appendix C. Migrating Applications from PHP4 to PHP5
Configuration
Object-Oriented Programming (OOP)
New Behavior of Functions
Further Reading
Appendix D. Good Programming Techniques and Performance Issues
Common Style Mistakes
Common Security Concerns
Style and SecurityLogging
Summary
Appendix E. Resources and Mailing Lists
Relevant Websites
Mailing Lists and Newsgroups
Index
SYMBOL
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

Accessing XML Data Using SimpleXML

SimpleXML is an extension that provides a simplified, very convenient interface for extracting XML data with minimum fuss or overhead and associating it with ordinary PHP objects that can then be manipulated or accessed using standard PHP tools and techniqueswithout the need for an additional set of functions or properties provided by an extension.

Because SimpleXML is compiled into PHP5 distributions by default, unless your operating system vendor has disabled it, SimpleXML should already be easily available to you without any additional work on your part if you are using PHP5.

SimpleXML is not available to users of PHP4.

Using SimpleXML in PHP Scripts

To use SimpleXML, you need only create a SimpleXMLElement object variable containing XML data. After XML data has been loaded, any value in the object tree can be accessed the same as you would access arrays or other variable data in PHP, as you'll see in the next section.

To create a SimpleXMLElement object and load XML data into it, you can use either of two functions, depending on your needs and the way in which your XML data is stored and accessed:

  • Use simplexml_load_file() if your XML data needs to be loaded and parsed from a text file. Pass the pathname of the file as an argument; the SimpleXMLElement object will be returned if SimpleXML is able to load and parse the file.

  • Use simplexml_load_string() if you have a PHP string variable or constant that you want to parse into a SimpleXMLElement object; the resulting SimpleXMLElement object will be returned if SimpleXML is able to parse the string data.

  • Use simplexml_import_dom() if you have a DomDocument object containing an XML object tree that you want to parse into a SimpleXMLElement object; the resulting SimpleXMLElement object will be returned if SimpleXML is able to import the DomDocument object.

To access data or elements in the XML object tree after it has been loaded and parsed into a SimpleXMLElement object, use these techniques:

  • To access element values, call nodes of the XML tree by name as if they were properties of the SimpleXMLElement object. The value of the element will be returned as an element object.

  • In cases where more than one element of a given name exists at the same level, include in brackets the number of the element that you want to access, as though the element in question was an array.

  • To access element attributes, call nodes of the XML tree by name as necessary, taking care to include the name of the attribute in brackets, as though the final element in the list was an array. The value of the element attribute in question will be returned as an element object.

Some examples of these techniques on a SimpleXMLElement object called $my_xml are shown in Table 9.10.

Table 9.10. Accessing Element Values Using SimpleXML

Sample

Meaning

$my_xml->title

Returns an element object containing the value of the top-level <title> element.

$my_xml->car->engine->displacement

Returns an element object containing the value of the <displacement> element that appears within the <engine> element that appears within the <car> element.

$my_xml->book[4]->author

Returns an element object containing the value of the <author> element that appears within the fourth <book> element.

$my_xml->book[4]->author['gender']

Returns an element object containing the attribute value for the gender attribute of the <author> element that appears within the fourth <book> element.


As you can see, SimpleXML provides for perhaps the cleanest, easiest-to-use interface for accessing XML data within PHP scripts.

Additional Notes About SimpleXML in PHP Scripts

In spite of the apparent simplicity presented by the SimpleXML interface, a few additional details should be supplied to prospective PHP5 with SimpleXML script writers:

  • Because SimpleXML returns an element object each time you access an element or attribute value, you must remember in many cases to cast the object to a string before making comparisons against string objects or string literals. This can be done simply by prefixing the object access with (string), as shown in this example:

    if ((string)$my_xml->book[4]->title == 'War and Peace') {
        echo 'Book four is by Tolstoy, we must pause here!';
        exit;
    }
    

  • SimpleXML objects can be manipulated in many of the same ways that other PHP objects can, including techniques such as iteration. For example, it wouldn't be uncommon to see a SimpleXML object included in a loop this way:

    foreach ($my_xml->book as $book) {
        echo 'Book is called ', $book->title;
        echo 'Book is by ', $book->author;
    }
    

  • When using SimpleXML, you can also use XPath patterns of the type discussed earlier in reference to XSLT templates (see Table 9.2). To do so, use the xpath() property with the pattern whose value you want to access:

    $my_address = (string)$my_xml->xpath(//smallsville//phone_book/john_smith);
    

  • As you might expect, you can also set element and attribute values when using SimpleXML, provided you have already loaded an XML tree into a SimpleXMLElement object. Simply assign values as you would to any other variable:

    $my_xml->personal_data->phone_number = '123-456-7890';