How to Read an RSS Feed With PHP

<?php
include("../includes/config.php");
include("../includes/dbcon.php");

$tt_res=mysql_query("SELECT *
FROM `rss_data`");

$num = mysql_num_rows($tt_res);
if($num!=0)
{
$tt="TRUNCATE TABLE `rss_data`";
mysql_query($tt);
}



//get the q parameter from URL
$q="yy";

//find out which feed was selected
if($q=="Google")
  {
  $xml=("http://news.google.co.in/news?pz=1&cf=all&ned=in&hl=en&topic=s&output=rss");
  }
elseif($q=="yy")
  {
  $xml=("http://in.news.yahoo.com/rss/cricket");
  }

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;



//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=5; $i++)
  {
  $item_title=$x->item($i)->getElementsByTagName('title')
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_link=$x->item($i)->getElementsByTagName('link')
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_desc=$x->item($i)->getElementsByTagName('description')
  ->item(0)->childNodes->item(0)->nodeValue;
 
  $item_title1=addslashes($item_title);
   $item_desc1=addslashes($item_desc);
 
echo $kk="INSERT INTO `rss_data` (
`item_title` ,
`item_desc`
)
VALUES (
 '".$item_title1."', '".$item_desc1."'
)";

mysql_query($kk);


  }
?>

mysqli Fetch Methods

If you prefer different MySQL fetch methods, they're also in mysqli. Given the same query of SELECT username FROM users, these example functions all print the same results:
// Fetch numeric arrays:

while ($row = mysqli_fetch_row($result)) {

    print $row[0] . "\n";

}



// Alternative syntax:

while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {

    print $row[0] . "\n";

}



// Alternative associative array syntax:

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

    print $row['username'] . "\n";

}



// Both numeric and associative:

while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {

    print $row[0] . "\n";

    print $row['username'] . "\n";

}



// Fetch as "object"

while ($row = mysqli_fetch_object($result)) {

    print $row->username . "\n";

}

XML Extensions in PHP 5

SimpleXML
A new PHP 5-only extension that excels at parsing RSS files, REST results, and configuration data. If you know the document's format ahead of time, SimpleXML is the way to go. However, SimpleXML supports only a subset of the XML specification.

XPath
This extension allows you to query XML documents like you're searching a database, to find the subset of information that you need and eliminate the unnecessary portions.


 XSLT
A way to take XML documents and transform them into HTML or another output format. It uses XML-based stylesheets to define the templates. XSLT is easily shared among different applications, but has a quirky syntax.

 

  • Reading XML into a tree
  • Reading XML from a stream
  • Creating new XML documents
  • Searching XML with XPath
  • Changing XML into HTML or other output formats with XSLT
  • Validating XML to ensure it conforms to a specification



    Example XML address book
    <?xml version="1.0"?>
    
    <address-book>
    
        <person id="1">
    
            <!--Rasmus Lerdorf-->
    
            <firstname>Rasmus</firstname>
    
            <lastname>Lerdorf</lastname>
    
            <city>Sunnyvale</city>
    
            <state>CA</state>
    
            <email>rasmus@php.net</email>
    
        </person>
    
    
    
        <person id="2">
    
            <!--Zeev Suraski-->
    
            <firstname>Zeev</firstname>
    
            <lastname>Suraski</lastname>
    
            <city>Tel Aviv</city>
    
            <state></state>
    
            <email>zeev@php.net</email>
    
        </person>
    
    </address-book>
     
     
     



    $dom = new DOMDocument;
    
    $dom->preserveWhiteSpace = false;
    
    $dom->load('address-book.xml');
    
    
    
    $root = $dom->documentElement;
    
    
    
    foreach ($root->childNodes as $person) {
    
        process($person);
    
    }

     

    The childNodes attribute is not an array, but a DOMNodeList object. The item( ) method allows you to access individual items, and the length property tells you the number of items in the list.
    This code is equivalent to the foreach loop:
    $people = $root->childNodes;
    
    
    
    for ($i = 0; $i < $people->length; $i++) {
    
        process($people->item($i));
    
    }


Tips for Optimizing CSS

1. Replace inline style with type selectors to target multiple instances of identical
elements.
2. Use descendant selectors to avoid inline classes.
3. Group selectors with common declarations.
4. Group declarations with common selectors.
5. Combine common styles into shared classes.
6. Use inheritance to eliminate duplicate declarations.
7. Use CSS shorthand to abbreviate rules and colors.
8. Abbreviate long class and ID names.
9. Use CSS2 and CSS3.x techniques.
10. Replace JavaScript behavior with CSS techniques.
In addition, you can eliminate extraneous whitespace by removing tabs, comments,
and returns.


Web pages that use inline style pepper HTML code with unnecessary font and style
tags. This effectively hardcodes the presentation directly within the HTML. Unless
the style is used only once, it is more efficient to create a CSS rule and target all elements
of a certain kind with type selectors (i.e., p, ul, h2, etc.). For example, this:




<h2 style="font-size:1.2em;color:red;">Little red Corvette</h2>
<h2 style="font-size:1.2em;color:red;">Baby you're much too fast to embed</h2>
<h2 style="font-size:1.2em;color:red;">Little red Corvette</h2>
<h2 style="font-size:1.2em;color:red;">You need a love that's gonna last</h2>
becomes this, by abstracting the inline style to a block style:
<style type="text/css"><!--
#main h2{font-size:1.2em;color:red;}
--></style>
The corresponding HTML cleans up to this:
<div id="main">
<h2>Little red Corvette</h2>
<h2>Baby you're much too fast</h2>
<h2>Little red Corvette</h2>
<h2>You need a love that's gonna last</h2>
</div>
 

Note how clean the code becomes after you remove the inline styles. This CSS technique
also helps search engine optimization (SEO) by boosting keyword density and
prominence.

Advanced SQL

15.1 Exploring with SHOW

The SHOW command is useful for exploring the details of databases, tables, indexes, and MySQL. It's a handy tool when you're writing new queries, modifying database structure, creating reports, or understanding how your MySQL server is performing. The SHOW command isn't part of the SQL standard and is MySQL-specific. It can be used in several ways:

SHOW DATABASES
Lists the databases that are accessible by the MySQL server. You will only see those databases that you have access to, unless you have the SHOW DATABASES privilege; privileges and user rights are discussed later in this chapter.

SHOW TABLES
Shows the tables in the database, after a database has been selected with the use command.

SHOW TABLE STATUS
Provides information about all tables in the current database, including the table type, number of rows, how the rows are stored, average row length, size of the datafile, next auto_increment value (if applicable), creation time, last modification time, and any extra options used with CREATE TABLE.

SHOW CREATE TABLE tablename
Shows the CREATE TABLE statement that was used to create the table tablename. The output always includes any additional information automatically added or changed by MySQL during the creation process, such as the table type and character set used.

SHOW OPEN TABLES
Shows which tables the server currently has open and which tables are locked.

SHOW COLUMNS FROM tablename
Shows the attributes, types of attributes, key information, whether NULL is permitted, defaults, and other information for a table tablename. The alias DESCRIBE table produces the same output.

SHOW INDEX FROM tablename
Presents the details of all indexes on the table tablename, including the PRIMARY KEY. It shows (amongst other information) what the attributes are that form each index, whether values in the index uniquely identify rows, how many different values there are in the index (the cardinality), and the index data structure used (usually a B-tree).

Using mysql_fetch_array fanc

we accessed attributes in order using the foreach loop statement. In many cases, you'll also want to access the attributes in another way, and this is usually best achieved by using the attribute names themselves. It's much easier to remember that you want to show the user the vintage year, the wine's name, the varieties, and the price, than to remember you want to show attributes four, two, six, and one from the SELECT statement. It's also a much better programming methodology because your code will be independent of the structure of the SQL statement and it'll be more readable. What's more, it's faster to access only the values you need.

$result = mysql_query("SELECT winery_name, phone, fax FROM winery");



while($row = mysql_fetch_array($result))

{

   print "The {$row["winery_name"]} winery's fax is {$row["fax"]}". 

   print "Their phone is {$row["phone"]}.\n";

}

MySQL Database Using PHP

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 <title>Wines</title>
 </head>
<body> <pre>
<?php
 // (1) Open the database connection
$connection = mysql_connect("localhost","fred","shhh");
// (2) Select the winestore database
mysql_select_db("winestore", $connection);
 // (3) Run the query on the winestore through the connection
$result = mysql_query ("SELECT * FROM wine", $connection);
// (4) While there are still rows in the result set, fetch the current
// row into the array $row
 while ($row = mysql_fetch_array($result, MYSQL_NUM))
{ // (5) Print out each element in $row, that is, print the values of
// the attributes
foreach ($row as $attribute)
print "{$attribute} ";
 // Print a carriage return to neaten the output print "\n"; }
?>
</pre>
</body>
</html>

Connect to the server with the MySQL function mysql_connect( ) .We use three parameters here: the hostname of the database server, a username, and a password. Let's assume here that MySQL is installed on the same server as the scripting engine and, therefore, localhost is the hostname. If the servers are on different machines, you can replace localhost with the domain name of the machine that hosts the database server.

The function mysql_connect( ) returns a connection resource that is used later to work with the server. Many server functions return resources that you pass to further calls. In most cases, the variable type and value of the resource isn't important: the resource is simply stored after it's created and used as required. 

Configuring the Connection Mysql

<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser',
'mypassword');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.';
include 'output.html.php';
exit();
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

If PHP is unable to connect to your MySQL server, or if the username and password
you provided are incorrect, you’ll instead see a similar screen to that in Figure 4.7.
To make sure your error-handling code is working properly, you might want to
misspell your password intentionally to test it out.

When an exception is caught, the value stored
in that variable is actually another PHP object; in fact, all exceptions are represented
by PHP objects! Like the PDO object we have stored in $pdo, the PDOException object
has properties we can access and methods we can call.

MySQL Data on the Web

Before we leap forward, it’s worth taking a step back for a clear picture of our ultimate
goal. We have two powerful tools at our disposal: the PHP scripting language
and the MySQL database engine. It’s important to understand how these will fit
together.

The whole idea of a database driven website is to allow the content of the site to
reside in a database, so that content may be pulled dynamically from the database
to create web pages for viewing on a regular browser. So, at one end of the system
you have a visitor to your site using a web browser to request a page. That browser
expects to receive a standard HTML document in return.

Just so it’s clear and fresh in your mind, this is what happens when there’s a visitor
to a page on your database driven website:
1. The visitor’s web browser requests the web page from your web server.
2. The web server software (typically Apache) recognizes that the requested file
is a PHP script, so the server fires up the PHP interpreter to execute the code
contained in the file.
3. Certain PHP commands (which will be the focus of this chapter) connect to the
MySQL database and request the content that belongs in the web page.
4. The MySQL database responds by sending the requested content to the PHP
script.
5. The PHP script stores the content into one or more PHP variables, then uses
echo statements to output the content as part of the web page.
6. The PHP interpreter finishes up by handing a copy of the HTML it has created
to the web server.
7. The web server sends the HTML to the web browser as it would a plain HTML
file, except that instead of coming directly from an HTML file, the page is the
output provided by the PHP interpreter. The browser has no way of knowing
this, however. From its perspective, it’s requesting and receiving a web page
like any other.

Here’s how you use PDO to establish a connection to a MySQL server:
new PDO('mysql:host=hostname;dbname=database', 'username',
'password')

Create Dynamic Database Access Objects

Some simple PHP that makes for a surprisingly robust script

<?php
require_once( "DB.php" );
$dsn = 'mysql://root:password@localhost/books';
$db =& DB::Connect( $dsn, array() );
if (PEAR::isError($db)) { die($db->getMessage()); }

class DBRecord
{
  var $h;

  public function DBRecord( $table, $id )
  {
   global $db;
   $res = $db->query( "SELECT * from $table WHERE id=?", array( $id ) );
   $res->fetchInto( $row, DB_FETCHMODE_ASSOC );
 $this->{'h'} = $row;
  }
  public function _ _call( $method, $args )
  {
 return $this->{'h'}[strtolower($method)];
  }
  public function _ _get( $id )
  {
 return $this->{'h'}[strtolower($id)];
  }
}
?> 
 
 
 

A simple script that tests the database access script
<?php require_once( "DBrecord.php" );
 $rec = new DBRecord( "author", 2 );
print $rec->Name()."\n";
?>

PHP 5 represents a substantial upgrade in terms of object-oriented support in the PHP language. Along with a number of upgrades in performance, PHP 5 has a major upgrade in the ability to create dynamic classes. These are classes where the methods and attributes change from object to object. This can be very handy in building database applications.