advanced php & rss utilizing xml, rss, and php. xml (extensible markup language) xml is the...

25
Advanced PHP & Advanced PHP & RSS RSS Utilizing XML, RSS, and PHP Utilizing XML, RSS, and PHP

Upload: magnus-shannon-baldwin

Post on 03-Jan-2016

279 views

Category:

Documents


1 download

TRANSCRIPT

Advanced PHP & Advanced PHP & RSSRSS

Utilizing XML, RSS, and PHPUtilizing XML, RSS, and PHP

XML (eXML (eXXtensible tensible MMarkup arkup LLanguage)anguage)

XML is the language of all RSS feeds and XML is the language of all RSS feeds and subscriptionssubscriptions

XML is basically a way of separating data from XML is basically a way of separating data from aestheticsaesthetics

XML is a “poor man’s” databaseXML is a “poor man’s” database

XML is similar to HTML, but you get to create XML is similar to HTML, but you get to create the tagsthe tags

““Self-describing” dataSelf-describing” data

XML PresentationXML Presentation

XML can be used to present content in XML can be used to present content in different formats:different formats:

XHTML/HTML, PDF, Graphics, Mobile Devices, XHTML/HTML, PDF, Graphics, Mobile Devices, Text, MS OfficeText, MS Office

XML SyntaxXML Syntax

<order><order> ELEMENTELEMENT<sold-to><sold-to> CHILD ELEMENTCHILD ELEMENT

<person ID=“123”><person ID=“123”> ATTRIBUTE … VALUEATTRIBUTE … VALUE<lastname>Matthews</lastname><lastname>Matthews</lastname><firstname>Darell</firstname><firstname>Darell</firstname> TEXT (Darell)TEXT (Darell)

</person></person></sold-to></sold-to><sold-on>20120904</sold-on><sold-on>20120904</sold-on><item><item> START TAGSTART TAG

<price>29.95</price><price>29.95</price><book><book>

<title>JavaScript Lessons</title><title>JavaScript Lessons</title><author>Neilson, Jason</title><author>Neilson, Jason</title>

</book></book></item></item> END TAGEND TAG

</order></order>

XML as a DatabaseXML as a Database

XML data organized into elements, XML data organized into elements, attributes, and values (similar to tables, attributes, and values (similar to tables, fields, and elements)fields, and elements)

Works great for storing around 50 or less Works great for storing around 50 or less attribute/value pairsattribute/value pairs

Often used in JS slideshows (1 XML for Often used in JS slideshows (1 XML for settings, 1 for photos used) and Flash settings, 1 for photos used) and Flash animations (1 XML for settings telling the animations (1 XML for settings telling the flash movie what to do)flash movie what to do)

XPathXPath

XPath is a language which allows us to quickly XPath is a language which allows us to quickly access information in an XML document based access information in an XML document based on our knowledge of its structureon our knowledge of its structure

/child::student/child::student[$number=‘0001’]/child::student/child::student[$number=‘0001’]

Example:Example:

movie.xml, movie.php, actor.phpmovie.xml, movie.php, actor.php

XML Address BookXML Address BookCreate Create addressbook.phpaddressbook.php, which lists your name as an <h1>, then a , which lists your name as an <h1>, then a horizontal rulehorizontal rule

Create Create addressbook.xmladdressbook.xml, which will include 5 people and their contact , which will include 5 people and their contact information (name, address, city, state, zip, phone, email)information (name, address, city, state, zip, phone, email)

Create a drop-down list populated with names pulled from Create a drop-down list populated with names pulled from addressbook.xmladdressbook.xml using SimpleXMLElements. Once the user selects a using SimpleXMLElements. Once the user selects a name, they click “Search” to bring up that person’s contact name, they click “Search” to bring up that person’s contact information on a page called information on a page called contact.phpcontact.php..

The The contact.phpcontact.php page should display that person’s contact page should display that person’s contact information, again being pulled from the XML file using the API, in an information, again being pulled from the XML file using the API, in an organized table.organized table.

All PHP pages should be styled (in any manner you wish) using an All PHP pages should be styled (in any manner you wish) using an external CSS file.external CSS file.

XML Address BookXML Address Book

addressbook.phpaddressbook.php contact.phpcontact.php

SimpleXMLSimpleXML

PHP API that allows PHP to interact with XMLPHP API that allows PHP to interact with XML

Create an XML document, then use PHP to parse the Create an XML document, then use PHP to parse the document for filtering / querying.document for filtering / querying.

SimpleXMLElementSimpleXMLElement is the PHP parsing function is the PHP parsing function

Since RSS feeds use XML to describe data in the feed, Since RSS feeds use XML to describe data in the feed, we can use PHP to parse that feed for our usage, all we we can use PHP to parse that feed for our usage, all we need is the feed address and some knowledge of the need is the feed address and some knowledge of the XML structure.XML structure.

Item, title, description, linkItem, title, description, link

Podcasts are RSS feeds with attachmentsPodcasts are RSS feeds with attachments

Feed ParsingFeed Parsing

View the page http://sampsoncctech.info/cis115/feedView the page http://sampsoncctech.info/cis115/feed

View the XML source code (notice the element, child View the XML source code (notice the element, child elements, attributes, and values)elements, attributes, and values)

Most RSS feeds follow the same general structure Most RSS feeds follow the same general structure and element/attribute naming conventionand element/attribute naming convention

Use PHP to grab the contents of the feed and place Use PHP to grab the contents of the feed and place them into an HTML document for stylingthem into an HTML document for styling

<?php<?php$now = time();$now = time();$xml = new SimpleXMLElement(file_get_contents(“http://sampsoncctech.info/cis115/$xml = new SimpleXMLElement(file_get_contents(“http://sampsoncctech.info/cis115/

feed”));feed”));?>?>

Feed Styling and OutputFeed Styling and Output

Once you have PHP gathering the feed data, Once you have PHP gathering the feed data, now use HTML and PHP to style the outputnow use HTML and PHP to style the output

simplexmlelementdemoCIS115.phpsimplexmlelementdemoCIS115.php

PHP “foreach” statement to loop and grab each PHP “foreach” statement to loop and grab each feed article and put it into a list where the title feed article and put it into a list where the title is a link to the articleis a link to the article

<?php foreach ($xml -> channel -> item as $item) { ?><?php foreach ($xml -> channel -> item as $item) { ?><li><a href="<?php echo $item -> link; ?>"><li><a href="<?php echo $item -> link; ?>"><?php echo $item -> title; ?></a></li><?php echo $item -> title; ?></a></li><?php } ?><?php } ?>

Parsing Other RSS FeedsParsing Other RSS Feeds

Find an RSS feed, podcast, or vodcast online Find an RSS feed, podcast, or vodcast online with an accessible XML feed source pagewith an accessible XML feed source page

Use PHP to gather the feed data, then a Use PHP to gather the feed data, then a “foreach” statement to parse each child “foreach” statement to parse each child element of the XML feedelement of the XML feed

Use HTML to style the output of the PHP Use HTML to style the output of the PHP parsing into an ordered or unordered listparsing into an ordered or unordered list

PHP Data Types & PHP Data Types & OperatorsOperators

PHP doesn’t require you to specify data typePHP doesn’t require you to specify data type

You can initialize and declare variables in one You can initialize and declare variables in one lineline

$variable = “some value or string”;$variable = “some value or string”;echo $variable;echo $variable;

Data Types:Data Types:

String, Integer, Floating-Point, Exponential, String, Integer, Floating-Point, Exponential, Boolean, NULLBoolean, NULL

PHP ArraysPHP Arrays

Contains a set of data represented by a single Contains a set of data represented by a single variablevariable

Array names are often referred to with array Array names are often referred to with array operators ([ ]) at the end of the nameoperators ([ ]) at the end of the name

$variable = array(“element1”, “element2”, “element3”);$variable = array(“element1”, “element2”, “element3”);$variable[] = “element1”;$variable[] = “element1”;

Declare an array with $variable = Declare an array with $variable = array(values): and access elements within the array(values): and access elements within the array by using $variable[index];array by using $variable[index];

PHP Array ExamplePHP Array Example

<?php<?php$concerts = array($concerts = array(

“Rihanna”,“Rihanna”,“Taylor Swift”,“Taylor Swift”,“Kati Perry”,“Kati Perry”,“Maroon 5”);“Maroon 5”);

$concerts[ ] = “Ellie Goulding”;$concerts[ ] = “Ellie Goulding”; //adds more elements to the end of the array//adds more elements to the end of the array$concerts[2] = “Flo Rida”;$concerts[2] = “Flo Rida”; //alters or replaces existing array elements//alters or replaces existing array elements

echo “<p>The following “, count($concerts), “ concerts are scheduled: echo “<p>The following “, count($concerts), “ concerts are scheduled: </p><p>”;</p><p>”;

echo “$concerts[0]<br>”;echo “$concerts[0]<br>”;echo “$concerts[1]<br>”;echo “$concerts[1]<br>”;echo “$concerts[2]<br>”;echo “$concerts[2]<br>”;echo “$concerts[3]</p>”;echo “$concerts[3]</p>”;

?>?>

PHP ExpressionsPHP Expressions

Expression: a literal value or numberExpression: a literal value or number

Operands: variables and literals contained in an Operands: variables and literals contained in an expressionexpression

Literals: values such as a string or numberLiterals: values such as a string or number

Operators: symbols such as +, -, *, / that are Operators: symbols such as +, -, *, / that are used in expressions to manipulate operandsused in expressions to manipulate operands

PHP Operator Types:PHP Operator Types:array, arithmetic, assignment, comparison, array, arithmetic, assignment, comparison,

logical, logical, special, stringspecial, string

Building PHP ExpressionsBuilding PHP Expressions

Arithmetic Binary Operators: +, -, *, /, % Arithmetic Binary Operators: +, -, *, /, % (modulus)(modulus)

arithmeticbinaryoperators.phparithmeticbinaryoperators.php

Arithmetic Unary Operators: ++ (increment), -- Arithmetic Unary Operators: ++ (increment), -- (decrement)(decrement)

arithmeticunaryoperators.phparithmeticunaryoperators.php, , 100countdown.php100countdown.php, , 100countup.php100countup.php

Logical Operators: && (AND), || (OR), ! (NOT)Logical Operators: && (AND), || (OR), ! (NOT)

logicalexamples.phplogicalexamples.php

PHP Cash RegisterPHP Cash Register

cashregister.htmlcashregister.html

cashregister.phpcashregister.php

Type Casting in PHPType Casting in PHP

Type casting: a way to ensure that a variable is Type casting: a way to ensure that a variable is of the correct typeof the correct type

$SpeedLimitMiles = “55 mph”;$SpeedLimitMiles = “55 mph”;$SpeedLimitKilo = (int) $SpeedLimitMiles * 1.6;$SpeedLimitKilo = (int) $SpeedLimitMiles * 1.6;echo “$SpeedLimitMiles equals $SpeedLimitKilo.”;echo “$SpeedLimitMiles equals $SpeedLimitKilo.”;

To test whether a variable is of a given data To test whether a variable is of a given data type, you should instead use an “type, you should instead use an “is_*()is_*()” ” functionfunction

is_numeric(), is_string(), is_int(), is_double()is_numeric(), is_string(), is_int(), is_double()

Comparison Operator Comparison Operator ExampleExample

Comparison Operators:Comparison Operators:

<?php<?php$storedpassword = “mypassword”;$storedpassword = “mypassword”;$enteredpassword = “mypassword”;$enteredpassword = “mypassword”;if ($storedpassword == $enteredpassword) {if ($storedpassword == $enteredpassword) {

print “The entered password is correct!”;print “The entered password is correct!”;} else {} else {

print “The entered password was wrong!”;print “The entered password was wrong!”;}}

?>?>

Logical Operator ExampleLogical Operator Example

Logical Operators:Logical Operators:

<?php<?php$storedusername = “user”;$storedusername = “user”;$enteredusername = “user”;$enteredusername = “user”;$storedpassword = “mypassword”;$storedpassword = “mypassword”;$enteredpassword = “mypassword”;$enteredpassword = “mypassword”;if ($storedusername == $enteredusername AND $storedpassword == if ($storedusername == $enteredusername AND $storedpassword ==

$enteredpassword) {$enteredpassword) {print “The entered username and password are correct!”;print “The entered username and password are correct!”;

} else {} else {print “The entered username and password were wrong!”;print “The entered username and password were wrong!”;

}}?>?>

PHP Do … While LoopPHP Do … While Loop

Do…While (perform an action while a condition Do…While (perform an action while a condition is being met)is being met)

<?php<?php$num = 1;$num = 1;do {do {

echo “The number is: $num<br>”;echo “The number is: $num<br>”;$num++;$num++;

} while (($num > 0) && ($num < 400));} while (($num > 0) && ($num < 400));?>?>

PHP If…Else…If ConditionalPHP If…Else…If Conditional

If…Else…If (if this happens, do this, If…Else…If (if this happens, do this, else/otherwise, do this)else/otherwise, do this)

<?php<?php$mood = “sad”;$mood = “sad”;if ($mood == “happy”) {if ($mood == “happy”) {

print(“Oh, you’re happy”);print(“Oh, you’re happy”);} elseif ($mood == “sad”) {} elseif ($mood == “sad”) {

print(“Oh, you’re sad”);print(“Oh, you’re sad”);} else {} else {

print(“What are you then?”);print(“What are you then?”);}}

?>?>

PHP For LoopPHP For Loop

For (perform this action for a fixed number of For (perform this action for a fixed number of times)times)

<?php<?phpfor ($counter = 1; $counter <= 10; $counter ++) {for ($counter = 1; $counter <= 10; $counter ++) {

print(“$counter times 2 is “. ($counter * 2). “<br>”;print(“$counter times 2 is “. ($counter * 2). “<br>”;}}

?>?>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<?php<?php

for ($counter = -4; $counter<=10; $counter++) {for ($counter = -4; $counter<=10; $counter++) {if($counter==0) {if($counter==0) {

break;break; //can also use “continue;” to skip 0//can also use “continue;” to skip 0} else {} else {

$temp = 4000/$counter;$temp = 4000/$counter;echo “4000 divided by $counter is... $temp<br>”;echo “4000 divided by $counter is... $temp<br>”;

}}}}

?>?>

PHP Nested For LoopPHP Nested For Loop

Nesting one for loop inside of another to Nesting one for loop inside of another to perform vertical and horizontal actionsperform vertical and horizontal actions

<?php<?php //Multiplication Table//Multiplication Tableecho “<table style=‘border: 1px solid black;’> \n”;echo “<table style=‘border: 1px solid black;’> \n”;for ($y=1; $y<=12; $y++) {for ($y=1; $y<=12; $y++) {

echo “<tr> \n”;echo “<tr> \n”;for ($x=1; $x<=12; $x++) {for ($x=1; $x<=12; $x++) {

echo “<td style=‘border: 1px solid black; width: echo “<td style=‘border: 1px solid black; width: 25px; padding: 25px; padding: 4px; text-align: center;’>”;4px; text-align: center;’>”;

echo ($x * $y);echo ($x * $y);echo “</td> \n”;echo “</td> \n”;

}}echo “</tr> \n”;echo “</tr> \n”;

}}echo “</table>”;echo “</table>”;

?>?>