inls572_class7_techtopics_022608

Download Report

Transcript inls572_class7_techtopics_022608

Internet Applications
Spring 2008
Review
• Last week
– XHTML, Webservers
This week
• Tech-topic presentations - XML/RSS
• Introduction to programming
XML DC record
<?xml version=“1.0” encoding=“UTF-8”?>
<!DOCTYPE qualifiedDublinCore PUBLIC '-//OCLC//DTD QDC v.1//EN'>
<qualifiedDublinCore>
<Creator>Alliance of Baptists</Creator>
<Title>Alliance of Baptists Records, 1987 - 2001</Title>
<Source/>
<Language>en</Language>
<Coverage>2.1 linear feet</Coverage>
<Description>[Lots of text omitted]<Description>
<Rights>Collection is open.</Rights>
<Subject>Alliance of Baptists</Subject>
<Subject>Southern Baptist Alliance</Subject>
<Contributor/>
<Publisher>Z. Smith Reynolds Library, Wake Forest University</Publisher>
<Type>text/xml</Type>
<Relation>Alan P. Neely Papers, Z. Smith Reynolds Library, Relation>
<Identifier>http://zsr.wfu.edu/collections/digital/ead/allianceofbaptists.xml</Identifier>
</qualifiedDublinCore>
Encoding Schemes (XML)
• Required syntax
– Document type declaration
• <!DOCTYPE food SYSTEM "food.dtd">
• Optional but useful
– Processing instruction
• <?xml version="1.0"?>
– Elements
• <elementname></elementname> notation
• All elements must be closed <ex></ex> or <ex/>
– Attributes
• <element attribute=“attributevalue”/>
• Attributes must be enclosed in “”
– Text
• <ex>fieldcontent</ex>
Encoding Schemes (XML) - 2
• File attributes
– Elements are repeatable (if allowed by
DTD/Schema)
– An XML file can contain multiple “records”
– Certain characters like need to be
represented by escape sequences:
• & = &amp;
• &lt; = <
• &gt; = >
Encoding Schemes (XML) - 3
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>Sample RSS File</title>
<link>http://urltofile.xml</link>
<description>This is a sample</description>
<language>en-us</language>
<pubDate>Tue, 10 Jun 2003 04:00:00 GMT</pubDate>
<item>…</item>
<item>…</item>
<item>…</item>
<item>…</item>
</channel>
</rss>
XML Components
• XML data model definition
– Document Type Definitions (DTD)
– XML Schema
– Application Profiles
• XSL processing instructions
– Transformation to new format
– Powerful enough to serve as a simple
application development platform
RSS Example
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>NYT > Media and Advertising</title>
<link>http://www.nytimes.com/pages/business/media/index.html?partner=rssnyt</link>
<lastBuildDate>Tue, 26 Feb 2008 13:05:01 GMT</lastBuildDate>
<item>
<title>Nielsen Looks Beyond TV, and Hits Roadblocks</title>
<description>Nielsen wants households to let it eavesdrop on Web surfing and cellphone
use, but it is finding it a tough sell.</description>
<author>LOUISE STORY</author>
<guid
isPermaLink="false">http://www.nytimes.com/2008/02/26/business/media/26nielsen.htm
l</guid>
<pubDate>Tue, 26 Feb 2008 12:46:15 GMT</pubDate>
</item>
</channel>
</rss>
http://cyber.law.harvard.edu/rss/rss.html
DOM Example
•A Hierarchy of elements
•Family based inheritance
•Parent
•Child
•Sibling
•Element access by name
•document.getElementById("You")
Programming
• Definitions
• Concepts
• A programming framework
Definitions
• Programming Language
• “A formal language used to write instructions that can be
translated into machine language and then executed by a
computer.” (definitions)
• Scripting Language
•
•
•
•
Run-time (does not require compilation)
Restricted context (requires a specific environment)
Functional / Object oriented
Definitions
• Compiler / Interpreter
• A program that builds and executes a program.
Compilers create a self-executable file, interpreters read a
text script at run-time
Programming approaches
• Logical/structural programming
• Stream of consciousness
• Starts at line 1
• Procedural programming
• Uses functions, sub-functions, subroutines
• Encapsulation, modularization
• Object-oriented programming
• Further encapsulation
• Uses concepts of inheritance, modularity
The programming process
• Analyze the problem
• What do you want your program to do?
• What are your users expecting, what data do you have?
• Plan program flow/logic
• What steps need to occur, in what order?
• Useful tools include Step-Form, flowcharts,
pseudocode
• Code the program
• Create variables, routines, functions
• Compile/run the program
• Test, verify
• Release
and
Algorithms
• “An effective procedure for solving a problem
in a finite number of steps.”
• Sample Algorithm for an email form (Step
Form)
– Begin
• If form data is present then continue processing
– Get data from form (Subject, note, etc)
– If the subject doesn’t contain bad stuff then continue
processing
» Write subject, note to email function
» Send email
» If Email sent successfully then tell user that it did,
otherwise output the error code
– End
Algorithm elements
• Processes / Sequences
• Actions are ordered according to need
• Decision making / Selection
• If...Then...Else
– If today is Friday then go home early
– If username = mitcheet then allow access
• Repetition / Iteration / Looping
• While
– While the database returns data, print it out
• Foreach
– For Each piece of data returned, write it to a file
• Variables
• Placeholders for information to be used by program
• Often “initialized” with specific values (such as 0”
Creating an Algorithm
• Investigate
– Identify a specific process
• (sending email)
– Identify the major decisions
• (presence of data, appropriateness of data)
– Identify the loops
• What needs to happen several times?
– Identify variables
• Lay out the algorithm
– Design a sequence of steps incorporating the decisions from
step 1. Make changes as necessary
• Refine algorithm
– Implement changes noticed during run-through
– Group processes, variables
Decision making
• Single-Alternative / unary outcome
– If then
• Dual-Alternative / binary outcome
– If then else
• Multi-Alternative /x-ary outcome
– If then elsif elsif elsif
– Switch case statements
• Switch case1: case2: default:
Flowchart Examples
• Start / End
• Data
• Decision Making
• A process
Pseudo code
•
Input/output
–
•
Iteration
–
•
If <condition> then <statement> else
If <> then <> elsif <> elsif <> endif
Processing
–
•
Repeat Until, Dowhile /end dowhile, for/end for
Decision
–
–
•
Input, Read, Display
Add(+), subtract(-), compute, compare (<,=,>), set
Subroutines (functions/sub-functions)
–
Use to define sub processes:
•
EMAILTHIS:
–
–
–
–
•
Input email, subject, note
Send email
Set send result to output variable X
return X
Include in your pseudo code with a call statement
–
Call EMAILTHIS (email, subject, note)
PHP Overview
• Standard PHP Syntax review
– Structure, operators,
• Constructs needed for today
– Variables
• Scalar, Arrays, Objects
– Output
• Echo
– Loops
• Foreach, for($i)
– Built-in Functions
• DomXML functions
Language elements (Syntax)
• Syntax – grammar, order, structure of
program
– PHP syntax example
<? PHP
Function () { stuff }
$variablename;
End of Line markers (;)
//comments
?>
– Syntax has to be perfect!
– PHP is case specific
Standard PHP program
<html stuff.....>
<?php
//Beginning element
Example statement;
//Use a semicolon to end lines
$myvalue;
//A scalar variable
$myarray[1];
//An array with value 1 returned
$myObjectref->function()
//A function in an object
$myvalue = “hello”;
//Variable Assignment
echo (“stuff”);
//A standard PHP Function
?>
<html stuff.....>
//Ending Element
Variables
• Text
– Strings
• Numbers
– Integers (whole numbers)
– Floating point – (decimal numbers)
• Boolean
– True/False
Variables – single value
• Scalars – Single value variables
– Strings - $username = “mitcheet”
– Numbers $cost = 55.00
– Boolean $ready = True
Variables – multiple values
• Arrays – Multi-value variables
– Grouped in numerical order
• $email[1] = “[email protected]”
• $email[2] = “[email protected]”
– Grouped with text
• $email[1][“username”] = “[email protected]”
• $email[1][“realName”] = “Erik Mitchell”
– General syntax
• $email = array ( key=>value, key=>value)
• Arrays can be nested (think hierarchy)
Objects
• Objects components
– Methods (Functions)
– Fields (Variables)
• PHP syntax for objects
– $myObjectReference->fieldvalue
– $myObjectReference->objectFunction()
• DomXML Example
– $dom = domxml_open_file("http://....xml");
– $rsstag = $dom->get_elements_by_tagname("rss");
PHP Variable Operators
http://www.w3schools.com/php/php_operators.asp
PHP Comparison Operators
http://www.w3schools.com/php/php_operators.asp
Variable scope
• Depending on where you initialize a
variable, impacts what functions can
use it
– A variable initialized at the beginning of
your file is “global”
– A variable initialized within a function is
limited to the function.
PHP Output functions
• echo ‘my output text’;
– You can use ‘ or “ but they have special
meaning
• echo ‘my output’.$variable.’my output’
– Use the . To concatenate strings
• Debugging output
– print_r ($complexvariable)
• Prints a user readable array/object
Exercise 1
• Sample Program
– http://www.ils.unc.edu/~mitcheet/class_7ex
ercises/class7_ex1.txt
– Type in this program
– Upload to Ruby
– Run and look at sourcecode
– Try to create an echo statement that
outputs specific values of the variable
• echo $associativeArrayVariable[‘title’]
Looping
• Definition
• Loop structures allow re-execution of instructions with
multiple sets of data
• Examples
• Writing records from a database query onto a webpage
• Calculating cost, discounts, shipping on items in a
shopping cart
• Comparing values to make decisions
• Benefits
• declare logic and operational statements once & re-use
• Loops are the building blocks of structured programming
• Use a ‘main’ loop to control the program
Loop structures
• Components
• Loop control variable
– the variable that keeps changing ($i for example)
• Sentinel value
– the value which signals the end of the loop
• Loop control structures
– Do while, While, for, foreach
• Example
for($i=1; $i<=100; $i++) {
echo “hello world! <br/>”;
}
for() { }
$i = 1
$i < 100
$i++
echo “”;
Control structure
Variable declaration
Limit declaration
Increment declaration
operational statement
Nesting
• Use a mix of flow-control and decision
making functions to create complex
processes
• If -> then -> else
• Switch -> case -> default
• For -> next
• Do -> while
Functions
• Definition
– “A sequence of instructions for performing a
specific task” (freedictionary)
• Benefits
–
–
–
–
Modularization/Abstraction
Code re-use
Variable management (global, local)
Easier to troubleshoot and maintain
• Key concepts
– Global variables vs local variables
– Parameters
– Returned values
PHP Functions
• Examples
– Phpinfo(), for(), foreach(), echo.......
• Contents
– Name, Parameters, operations, return values
function myFunctionName (parameters)
Declaration
{
{
parameters;
operations;
return
variables;
Parameters passed to function
Operations (calculate, lookup, etc)
Return values to rest of program
}
}
The XMLParse object
• SimpleXML
– Standard in PHP5, but we are using PHP4 
– Today, we are relying on some extra code to make
things simple!
• What it does
– Reads in an XML file and breaks the DOM into an
array of variables
– Provides us methods to access XML values
• http://www.criticaldevelopment.net/xml/doc.php
XMLParse Example
<?php
// Include the code that makes simplexml work
require('./php_4_simplexml.php');
//Get the XML document loaded into a variable
$xml = file_get_contents('http://www.nytimes.com/services/xml/rss/nyt/Music.xml');
//Set up the parser object
$parser = new XMLParser($xml);
//Work the magic...
$parser->Parse();
//Echo the plot of the first <movie>
echo $parser->document->rss[0]->channel[0]->title[0]->tagData;
//Echo the plot of each <item> title
foreach($parser->document->channel[0]->item as $item)
{
echo $item->title[0]->tagData;
}
?>
XMLParse Example (2)
• Mixed array/object syntax
– $parser->document->channel[0]->item
• Available functions for an object
– tagData
– tagParents
– tagChildren
– tagAttrs
– tagName
Exercise 2
• In this example, we will create a
simplexml object and process some
data
– Get the SimpleXML file and and upload it to
your webspace
– Write the simplexml example program
Exercise 3 / homework
• Today we will add RSS feed parsing
functionality to our webpage from last week
– Create a program outline using
pseudocode/flowcharting
– Using the XMLParse functions, write the program
in php
– Program requirements
• Use XMLParse or another solution (DOMXML is much
more complicated but uses only embedded php functions)
• Your program should be able to output multiple RSS
feeds (looping).
• Your program should only show the first 10 elements of
the feed and provide a link to view more
Next week
• Technology Topics CSS/XSLT
• More on PHP