Exercise 3

advertisement

Class 8 Exercises

– XSL/CSS

Overview ................................................................................................................................................................. 1

Exercise 1 ................................................................................................................................................................ 2

Exercise 2 ................................................................................................................................................................ 2

Exercise 3 ................................................................................................................................................................ 4

Exercise 3 ................................................................................................................................................................ 5

Exercise 5 ................................................................................................................................................................ 9

Programming Reference ....................................................................................................................................... 12

XSL Syntax ....................................................................................................................................................... 12

XSL/PHP Function Comparison ........................................................................................................................... 13

Php syntax ............................................................................................................................................................. 13

Integration with HTML..................................................................................................................................... 14

PHP Operators .................................................................................................................................................. 14

PHP Variables ................................................................................................................................................... 14

PHP Loops / Control structures ........................................................................................................................ 15

Functions ............................................................................................................................................................... 15

Standard functions needed for these exercises.................................................................................................. 15

XMLParser functions (http://www.criticaldevelopment.net/xml/doc.php) ...................................................... 16

XML Simple functions – PHP 5 (ISIS) ............................................................................................................ 16

Example 1 template pages .................................................................................................................................... 16

Main template page: .......................................................................................................................................... 16

Site navigation page .......................................................................................................................................... 17

External CSS File .............................................................................................................................................. 17

Overview

The purpose of these exercises are to become more familiar with XML/XSL and CSS, and to get acquainted with using XSL transformations in PHP. All files for these exercises are available at: http://www.ils.unc.edu/~mitcheet/INLS572class_8exercises/

Ex1 – working with our templaes

Separate out css file

Create index.php

Insert logic to handle menu items

Ex2 – hello world

Ex3 – CSS – re-style

Background images;

Ex4 – xml based menu system

So if you have xml based menus, then php to look at values selected. . .body idv element.

Ex2 – create an RSS file of feeds, write XSL transform to match output of first app (client side)

Ex3 – write php parser – parameterize it

Ex4 – write feed aggregator – give the opportunity to do it in XSL or PHP

INLS572

2008

Spring 1

Exercise 1

In this exercise we will break our HTML file from previous exercises into three files, an external CSS stylesheet, an external navigation php page, and our main processing page.

1) external CSS stylesheet a.

Copy the content of the <style>…</style> tag into a new file. The new file should not have the style elements and should just start with css content b.

Save the file as class8_ex.css (or something you can remember). . . . c.

In the main html/php page where the <style> element was, use an include reference to point to the external stylesheet i.

<link rel="stylesheet" type="text/css" href="./class8_ex.css"/> d.

Post your external stylesheet and your updated template

2) External navigation file a.

Create a new PHP document. Copy the <ul> in the navigation <div> tag to the new file.

<?php echo <<<nav

<ul>

</ul>

<a bunch of copied li content/> nav;

?> b.

Save the file as site_nav.php c.

In your main php page, enter a reference to the content within your div: i.

<div id="nav"><?php include('./site_nav.php')?></div> d.

Save your main php page as INLS572_template.php. You can now base the remainder of your pages on this file. e.

Upload both files to Ruby and make sure everything is working

Exercise 2

In exercise 2 we will style up a static HTML page, using formatting and layout CSS elements. Discussion of each of these elements is in the CSS tutorial at w3schools ( http://www.w3schools.com/css/default.asp

). For this exercises, a good reference resource ishttp://www.w3schools.com/css/css_reference.asp. Our goal for this exercise is to explore positioning elements and practice content formatting.

1) Grab the html page http://www.ils.unc.edu/~mitcheet/INLS572_class8exercises/csslayout_nostyle.html

.

Save it to your machine. We will work with this html page for the remainder of the exercise. a.

Notice the semantic structure of the page. The page consists of <h1>, <h2>, and <p> elements all wrapped within a <div> element.

2) Style the headers. In the <style> tag, add a entry for h1 and h2 h1 { font-size: 2em;

} h2 { font-size: 1em;

}

3)

Let’s hide all of our content and just play with floating two elements (the two p elements with classes) p { visibility:hidden; /* This hides all p elements */

INLS572

2008

Spring 2

} img { visibility:hidden; /* This hides all img elements */

}

.firstp { visibility:visible; position:relative; float:left; width: 50%;

}

.secondp { visibility:visible; position:relative;

/*Show all elements with .firstp class*/

/*position the element relatively*/

/*position the element on the left*/

/* Take up half of the screen */

/*Show all elements with .firstp class*/

/*position the element relatively*/ float:right; width: 50%;

/*position the element on the right*/

/* Take up half of the screen */

}

4) Try switching the float commands on these directives. What happens?

5) Notice that the .firstclass p text is not aligned at the top of the screen. This is because there is an image element that is being positioned within that p. To remove the image element from document flow add

“position:absolute;” to the img directive. Try taking out the visibility directive to see where the image appears. Notice that it appears right on top of the .firstp classed element. This is because it is

“absolutely” positioned and is out of the document flow for that p (but still exists within the context of that p).

6) Try moving the image around using left, right, and top directives. Play around with the values of these directives img { position:absolute; top:400px; left: 300px;

}

7) Lets unhide all of our P elements and set their width. Notice how the classed p elements keep their default behavior. p { width:50%;}

8) It is time to make this page look good. Let’s start by creating a nice banner at the top of the page: h1 { margin-bottom: 10px /*keep some padding between the h1 and other elements*/ font-size: 2em; border-bottom: #333333 thick solid;

/*make the font big*/

/*use border-bottom to give a nice horizontal line*/ background-image:url( http://sils.unc.edu/images/sils_logo.png

); /*set background image for the header*/ background-repeat:no-repeat; /*show the image only once */ text-align:right;

}

9) While we are here, lets add some padding to the <h2>. Add a margin directive to your h2 entry: margin: 10px

10px 10px 10px;

10) Now lets work on our image/paragraph layout. Notice how the image position messes up the text? We want to position all of our images on the right side of the page and have the text flow around it. We also want to set some spacing on our paragrphs.

p {

INLS572

2008

Spring 3

position:relative; margin: 0px 0px 40px 30px;

/*set our p positioning to relative*/

/*set some margins for spacing*/

} img { position:relative; float:right; margin: 0 10px 10px 10px; padding: 5px 5px 5px 5px;

/*also position our images relatively*/

/*always position our images to the right*/

/*set some margins*/

/*set some padding*/ border:#333333 thin solid; /*add a nice border to the image*/

}

11) Now, lets add a footer using our classed p (.footer)

.footer { float: left; margin: 20px; width: 100%; border-bottom: #333 medium solid;

} p.footer:before {

/*position our footer to the left*/

/*add some padding*/

/*make sure it spans the page*/

/*use our same horizontal line trick*/

/*add some content above our footer*/ content: "UNC School of Information and Library Science";

}

12) Finally, instead of having a page this wide, we want to center the contents and make it 600 pixels wide. In order to do this, we need to modify several of our elements: a.

Add a body directive body { text-align: center;

}

/*tells the document to center everything*/ b.

Add a div directive div { margin: 0 auto; width: 600px; text-align:left;

}

/*set a 0 top margin and automatic left and right margins*/

/*set a width*/

/*align all text within div to left*/

Exercise 3

In this exercise, we will re-create the “hello world” exercise using XML/XSL as a platform and Internet

Explorer as our interpreter. The files are ex3_xslstransform.(xml, xsl, php) and are accessible on http://www.ils.unc.edu/~mitcheet/INLS572_class8exercises

1) Create your XML file. This file follows a simple made up standard using root as a main element and message as

<?xml version="1.0" encoding="UTF-8"?>

<root>

<message>Hello World</message>

</root>

2) Create your XSL file. Notice the declaration of the xsl namespace in the stylesheet element. The main processing function of an xsl stylesheet is the <xsl:template match=””/> function. In XSL your main xsl function will match on your root path “/”. From there you can start calling new templates.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

INLS572

2008

Spring 4

<html>

<body>

<h1>

<xsl:value-of select="/root/message"/>

</h1>

<p>This is some static text in the XSL file</p>

</body>

</html>

</xsl:template>

</xsl:stylesheet>

3) Assign your XSL file to your XML file

<?xml-stylesheet type="text/xsl" href="./ex2.xsl"?>

4) You can either upload your two documents to ruby (and view in Internet Explorer) or just open the XML file in a web-browser. Alternatively, you can use an XML editor such as Exchanger to preview your transformation.

5) For part two of this exercise, we will create a PHP XSL transformation program. This program will perform the XML/XSL transformation server-side as opposed to having the transformation done client side. a.

PHP 4 can complete XML/XSL transformation using three functions domxml_open_file, domxml_xslt_stylesheet_file, and process(). Documentation on how this function works is available at ( http://us3.php.net/domxml_xslt_stylesheet_file ). Information on PHP5 and XSLT is available at (http://us3.php.net/manual/en/ref.xsl.php).

1) Create a new php file. You can use the template you created in exercise 1 or just start with a new file.

Enter the following code:

2) Upload the php page to Ruby and view in your webbrowser. The results should match Exercise 2.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Untitled Document</title>

</head>

<?php

?>

<body>

</body>

</html>

$xmlfile = domxml_open_file("./ex2.xml");

$xslfile = "./ex2.xsl";

$xslt = domxml_xslt_stylesheet_file($xslfile);

$htmloutput = $xslt->process($xmlfile); echo $htmloutput->dump_mem();

Exercise 4

In exercise 4 we will combine our CSS skills from exercise 1 with our XSL skills from exercise 2. XSL allows us to access XML document elements (using Xpath) and output these elements in a different format. It also supports string manipulation, some mathematical functions, and other programming concepts such as looping

INLS572

2008

Spring 5

and control structures. In this exercise we style an RSS feed from Flickr to and show it in our RSS reader application

The steps of this exercise are:

1) Look at Flickr images RSS feed

2) Create PHP script that will perform XSL transformation of the RSS feed

3) Create XSL file that will output the elements of the RSS feed as thumbnail images

4) Add CSS styling to the page to show the thumbnails

5) Add functionality to the XSL stylesheet to harvest more data from the page.

1) The Flickr Feed uses a namespace (media). The URL we will use for this exercise is: http://api.flickr.com/services/feeds/photos_public.gne?format=rss2 . If you go to http://www.flickr.com/services/feeds/docs/photos_public/ you will notice that there are several output standards (atom, rss, etc.) This exercise was developed using the RSS output format but if there is another style you want to work with give it a go. a.

We want to access several elements from this content so we need to figure out where those elements are. Find the location of each of these elements: i.

Feed Title ii.

Feed Link iii.

Thumbnail Image iv.

Photograph link v.

Image title

2) Create a simple php script that mirrors the one created in exercise 2. This script should use the flickr

RSS feed as its xml file ( http://api.flickr.com/services/feeds/photos_public.gne?format=rss2 ) and should call an XSL file that you will create in step 3. For a sample file see

(http://www.ils.unc.edu/~mitcheet/INLS572_class8exercises/ex4_flickr.txt)

3) Create an XSL file that accesses the appropriate elements in the XML feed and outputs them as an unordered list of images. You probably want to assign a class name to the <ul>. a.

<ul class=”thumbnail”><li><img src=””/></li><li><img src=””/></li></ul> b.

What follows is a sample XSL Stylesheet.

<?xml version="1.0" encoding="UTF-8"?>

<!--notice the declaration of the media namespace in the xsl declaration-->

<xsl:stylesheet version="1.0"

xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:media="http://search.yahoo.com/mrss/">

<xsl:template match="/"> <!-- use our default template -->

<!-- we have to know something about the Flickr RSS feed since it uses a namespace -->

<!--Get feed title and link information -->

<xsl:variable name="feedTitle" select="/rss/channel/title"/>

<xsl:variable name="feedUrl" select="/rss/channel/link"/>

<ul class="thumbnail">

<!-- Loop through each item element and output the images as an unordered list -->

<xsl:for-each select="//item">

<!-- getting the thumbnail path as a variable makes creating the img element easier -->

<xsl:variable name="thumbSrc" select="./media:thumbnail/@url"/>

<xsl:variable name="flickrLink" select="./link"/>

<xsl:variable name="thumbTitle" select="./title"/>

<li><a class="thumbs" href="{$flickrLink}">

INLS572

2008

Spring 6

<img alt="{$thumbTitle}" src="{$thumbSrc}"/></a></li>

</xsl:for-each>

</ul>

</xsl:template>

</xsl:stylesheet>

4) Save the php and xsl files and upload them to Ruby. Take a look at the output. It can be difficult to debug XSL errors using Ruby so be sure to read each error message, usually the third or fourth entry gives you a clue to what went wrong.

5) In order to show these thumbnail images correctly, we want to add some css styling to them. a.

We need to alter our display of the <ul> element: ul.thumbnail { float: left; /*push the content onto the left side of the page*/ background-color:#ffffff; /*set the background to white*/

} list-style:none; /*remove the bullet points*/ b. Now tell our list elements to display inline ul.thumbnail li {

} display:inline; /*Inline means it will wrap in a closed space */ b.

Finally, we need to style our link elements ul.thumbnail li a { width: 80px; margin-right: 10px; margin-bottom: 10px; float:left;

/*Set a link width*/

/*create some margins*/

/*have our images wrap from the left*/ padding: 4px 4px 9px 4px; /*set some padding around each image*/ border: 1px solid #ccc; border-top-color: #ddd; border-bottom-color: #bbb; background-color: #fff;

/*create a nice border*/

/*provide some style to the border*/

/*set a default background color*/

}

6) Say we wanted to provide a hover event for our thumbnails to show the larger image. In order to accomplish this, we need to a.

Harvest more data from the RSS feed b.

Include that data in our XHTML markup c.

Style the output d.

In Exercise 3 we will work with CSS to add background images to our page and style our RSS displays

1) we will use the Flickr rss services http://www.flickr.com/services/feeds/docs/photos_public/ http://api.flickr.com/services/feeds/photos_public.gne?format=rss2

In this exercise, we will re-write our PHP based RSS reader in XML/XSL. This will require the creation of an

XML file to store the RSS feed URLS that we want to access and the creation of XSL processing templates to get the RSS data.

1) Create an XML file that will contain our RSS feeds

INLS572

2008

Spring 7

a.

Use the RSS standard to Create an XML file that points to other RSS files. This will be our main data source for our XSL stylesheet. In this example, I only implemented the title and link elements of RSS.

<?xml version="1.0"?>

<rss version="2.0">

<channel>

<item>

<title>NYT Health</title>

<link>http://www.nytimes.com/services/xml/rss/nyt/Research.xml</link>

</item>

<item>

<title>CNN Entertainment</title>

<link>http://rss.cnn.com/rss/cnn_showbiz.rss</link>

</rss>

</item>

</channel>

2) Create an XSL file which processes that XML file, retrieves our feeds, and outputs them to the webpage a.

Our XSL file needs to i.

Output appropriate html information (<html><head><body><div>…). We can use our

HTML template file to make this easier! ii.

Have a main processing template that accesses each <item> element in our XML file iii.

Grabs the <link> element data and use the document() function to create an XPath statement to get data from that URL. iv.

Get the title and url from the remote feed and output them as unordered list elements v.

End the loop and move to the next feed vi.

A suggested approach is:

INLS572

2008

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

<xsl:for-each select="/rss/channel/item">

<xsl:variable name="feedUrl"><xsl:value-of select="./link"/></xsl:variable>

<div class="rssfeed">

<a href="{$feedUrl}">

<h1>

<xsl:value-of select="document(concat($feedUrl,''))/rss/channel/title/text()"/>

</h1>

</a>

<ul>

<xsl:for-each select="document(concat($feedUrl,''))/rss/channel/item">

<xsl:sort select="title"/>

<xsl:variable name="itemUrl"><xsl:value-of select="./guid"/></xsl:variable>

<li><a href="{$itemUrl}"><xsl:value-of select="./title"/></a></li>

</xsl:for-each>

</ul>

</div>

</xsl:for-each>

</xsl:template>

Spring 8

</xsl:stylesheet> b.

Notice the mix of HTML/XSL in the stylesheet. This works fine as long as your HTML is well formed. While you can view the output of your xsl by opening the file in Internet Explorer, trying to view ex4.xml in your webbrowser from Ruby will return no remote data.

3) To view your exercise 4 xml/xsl pages via ruby, modify the php script you created in exercise 3 to point to these files.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title> RSS Feed Aggregator </title>

<link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" />

<meta name="DC.title" content="Sample XHTML Page"/>

<meta name="DC.author" content="Erik Mitchell"/>

<link rel="stylesheet" type="text/css" href="./class8_ex.css"/>

</head>

<body id="body_rss">

<div id="header">

<h1>RSS aggregation service</h1>

</div>

?>

<div id="nav"><?php include('./site_nav.php')?></div>

<div id="main">

<h2>RSS Feed Reader</h2>

<?php

$xmlfile = domxml_open_file("./ex4.xml");

$xslfile = "./ex4.xsl";

$xslt = domxml_xslt_stylesheet_file($xslfile);

$htmloutput = $xslt->process($xmlfile); echo $htmloutput->dump_mem();

</div>

</body>

</html>

Exercise 5

In exercise 5, we will modify our menu system to be driven by XML data. We will also add a CSS event

(hover) to the menu system. The purpose of this exercise is to allow us to store our subscribed RSS feeds in an

XML file and to be able to access these via our menu system.

1) Create the XML file

2) Modify the navigation page

3) Create the hover style

4) Modify our php script to follow those urls.

INLS572

2008

Spring 9

In this exercise, we will add ‘feed aggregation’ as a feature of our XSL-based application.

In order to do this we need to modify our XML file to add a ‘search aggregation’ feature and we need to modify our XSL template to process these search templates against our RSS data.

1) The XML file

<?xml version="1.0" encoding="UTF-8"?>

<?xml-stylesheet type="text/xsl" href="ex5.xsl"?>

<rss>

<channel>

<item>

<title>NYT Health</title>

<link>http://www.nytimes.com/services/xml/rss/nyt/Research.xml</link>

</item>

<item>

<title>CNN Entertainment</title>

<link>http://rss.cnn.com/rss/cnn_showbiz.rss</link>

</item>

<item>

</item>

<title>NYT Music</title>

<link>http://www.nytimes.com/services/xml/rss/nyt/Music.xml</link>

<item>

<title>Rolling Stones New Music</title>

<link>http://www.rollingstone.com/blogs/breaking/rss.xml</link>

</item>

<item>

<title>BBC Breaking News</title>

<link>http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml</link>

</item>

<aggregationSearch>

<aggTitle>British News</aggTitle>

<aggSearch>Brit</aggSearch>

<aggSearch>UK</aggSearch>

</aggregationSearch>

<aggregationSearch>

<aggTitle>Health News</aggTitle>

</aggregationSearch>

</channel>

<aggSearch>Health</aggSearch>

<aggSearch>fitness</aggSearch>

</rss>

2) The XSL File

3) Stylesheet functions: a.

<xsl:call-template name=”search”/>

INLS572

2008

Spring 10

i.

This function is used to call a template (think function) that is defined elsewhere in the xsl stylesheet. b.

<xsl:variable name=”varname” select=”value”/> i.

The variable function assigns variables in XSL. Another acceptable form is <xsl:variable name=”varname”>value</xsl:variable> ii.

Once assigned, variables cannot be changed in XSL! iii.

In XSL 1.0, there are not multiple variable types. This is different in XSL 2.0 c.

<xsl:value-of select=”/a/valid/xpath/statement”/> i.

This function inserts a called value from an XML file d.

Document(concat($feedUrl, ‘’)) i.

This combination of functions accesses an external document ii.

The document() function is used in an Xpath statement to tell the XSL processor to look at the external XML file. In our case, we are looking at remote RSS feeds. iii.

The concat(val1, val2, val3) function concatenates strings together. In developing this exercise, I had difficulty getting the XSL processor to construct the document() function without adding a concatenation string but this should not be necessary. e.

Contains() i.

Contains is a test often used in an if or for each statement ii.

Contains(string1, string2) tests if string1 contains string2. This is a simple way of doing a search in XSL f.

Translate() i.

The translate function translates characters from one value to another. In this case, we are translating all uppercase characters to lower case characters. XSL 2.0 has two functions lower-case and upper-case which would do this for us but PHP4 does not support XSL 2.0 functions.

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">

<xsl:template match="/">

<xsl:call-template name="search"/>

</xsl:template>

<xsl:template name="search">

<xsl:for-each select="/rss/channel/aggregationSearch">

<xsl:variable name="feedTitle"><xsl:value-of select="./aggTitle"/></xsl:variable>

<div class="rssfeed">

<h1><xsl:value-of select="$feedTitle"/></h1>

<ul>

<xsl:for-each select="./aggSearch">

<xsl:variable name="feedSearch" select="."/>

<xsl:for-each select="/rss/channel/item">

<xsl:variable name="feedUrl"><xsl:value-of select="./link"/></xsl:variable>

<xsl:for-each select="document(concat($feedUrl,''))/rss/channel/item">

<xsl:sort select="title"/>

INLS572

2008

Spring 11

</rss>

<xsl:if test="contains(translate(.,

'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), translate($feedSearch,

'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'))">

<xsl:variable name="itemUrl"><xsl:valueof select="./guid"/></xsl:variable> select="./title"/></a>

<li><a href="$itemUrl"><xsl:value-of

</li>

</xsl:if>

</xsl:for-each>

( <xsl:value-of select="../title"/> )

</ul>

</xsl:for-each>

</xsl:for-each>

</div>

</xsl:for-each>

</xsl:template>

</xsl:stylesheet>

4.

Create the PHP file to output this data.

5.

It is time we modify the php script that translates XML/XSL data to accept parameters. This way we can have this function parse the documents on an as-needed basis.

Programming Reference

XSL Syntax

XSL is similar to XML/XHTML in its syntax. Proper element nesting, comments, use of double quotes, etc follow XML rules. In XSL, like HTML, elements and attributes have special functional value that is provided by XSL transformation engines (in the same way that a browser provides HTML with its functionality).

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> XSL Declaration

<!-- A comment -->

<xsl:template match="/"> <!-- The main template, match is an attribute with an xpath value-->

<html> <!-- Html can be used within XSL with no problem -->

<body>

<h1>

</h1>

<xsl:value-of select="/root/message"/> <!-- insert dynamic data -->

<p>This is some static text in the XSL file</p>

</body>

</html>

</xsl:template>

</xsl:stylesheet>

INLS572

2008

Spring 12

XSL/PHP Function Comparison

XSL Function PHP Function

<xsl:for-each select=”/valueinpath”> </xsl:foreach> Foreach ($array as $singlevalue) { }

<xsl:variable name=”varname” select=”varvalue”/> var $myvariable = “value”;

<xsl:choose><xsl:when test=””/><xsl:otherwise/> Switch { case “apple”: content; break;}

<xsl:include href=""/>

No Equivalent – Array would be an xml document

Require(‘./filename’);

Var $myarray = array(‘value1’, ‘value2’);

No Equivalent Object references $myobj->function() for ($i=0;$i<10; $i++) {code; } No easy solution – because you cannot change variables in XSL, you have to use recursion to continue calling a named template

XSL Looping Functions

XSL Variables

XSL Use with HTML

XSL Operators

XSL Templates

CSS Selectors

CSS Pseudoclasses

CSS Syntax

Php syntax

<?php

Example statement;

$myvalue;

$myarray[1];

$myObjectRef->function()

$myvalue = “hello”; echo (“stuff”);

?>

//Beginning element

//Use a semicolon to end lines

//A scalar variable

//An array with value 1 returned

//A function reference for an object

//Variable Assignment

//A standard PHP Function

//Ending Element

INLS572

2008

Spring 13

Integration with HTML

<html>

<head></head>

</body>

<?php

…php code

?>

</body>

</html>

PHP Operators

Assignment o $variable = “value”; o $i++ increment numeric value by 1 o $i-- decrement numeric value by 1

Comparison o == is equal to o >= is greater than or equal to o != is not equal to

PHP Variables

General o All variables start with $. o Variables can be single (scalar) or multi (array) valued o Variables have scope – in other words, they make sense only within the context of their program or function.

Scalars – single value variables o $mysinglevalue = “hello world” ;

Arrays o $mymultivalue = array(“value1”, “value2”) o $my multivalue[0] = value1;

Associative Arrays – (use names instead of numbers as placeholders) o $myarray[‘name’] = “Erik Mitchell”; o $mymultiarray[0][‘name] = “Erik Mitchell”;

Objects o Objects are a combination of variables, properties, and functions which are designed to simplify the programming process. For this exercise, the important thing to know about objects are how you call their properties and methods using the -> connection. o In the following example the object reference $dom is calling a specific function of their object (get_element_by_tagname). $feedhead is the resulting array. o When using object methods (such as in this example) you must pay attention to the type of variable returned. In this case an array of object references are returned. o $feedhead = $dom->get_elements_by_tagname("channel");

INLS572

2008

Spring 14

PHP Loops / Control structures

For Loop o For the variable $i begins at 0, is less than 10 and increments by one value o Syntax for ($i=0;$i++;$i<10) {

Php code

}

Foreach o Foreach value of $parentarray as $singlevalue o Syntax foreach($array as $singlevalue) {

Php code

}

Functions

PHP function quick reference - http://www.php.net/quickref.php

Standard functions needed for these exercises

1) Array() – creates an array variable (eg $myvar = array(‘val1’, ‘val2’);

2) echo //outputs content to the screen a.

echo “my interpolated values {$var1}”; //inserts the value of $var1 b.

echo ‘my non-interpolated value’ c.

echo “this”.”that”.$var1

//single quoted strings are not parsed

//use the . to concatenate strings

3) file_get_contents($filename) –retrieves a file and stores it in a variable.

4) foreach ($array as $singlevalue) { phpcode} a.

This function creates a loop which examines each element in an array.

5) for ($i=0;$i<10;$i++) {phpcode} a.

The For loop cycles through a loop a set number of times. As opposed to the foreach loop which creates a new variable for a specific value of an array each time through the loop, the for loop allows you to access array elements using the [] symbols (eg $arrayvariable[$i] retrieves the ith value).

6) var_dump($variable)

7) count($feedBody)

//outputs variables for debugging

//count the # of array elements

8) require() - retrieves and inserts external files. Use this to include the XMLParser functions that we use in exercise 2 and 3

INLS572

2008

Spring 15

XMLParser functions ( http://www.criticaldevelopment.net/xml/doc.php

)

1) $parser= new XMLParser($xml) a.

Creates a new object called $xml which inherits all the properties of the class XMLParser. This is somewhat complicated object oriented stuff but the key things to know here are i.

$parser is just a variable name which stores a reference to an object instead of a string ii.

XMLParser is a function which is defined in a library of code that we include iii.

New is a keyword in PHP which instatiates a new object iv.

$xml is just a string variable with XML data.

2) $parser->Parse(); a.

This is an OOP (object oriented programming) method for calling a function Parse for an object

$parser

3) $parser->document->channel[0]->title[0]->tagData; a.

This is an example of how you can retrieve data from your parser object once you have called the

Parse() function. The values of the string (document, channel…) depend on the XML structure you are pulling from. b.

XMLParser relies on a mixed array/object notation that is confusing and is much simpler in

PHP5. Don't worry too much about this now but understand that: c.

Document – object reference d.

Channel[0] – array reference (the first channel element) e.

Title[0] – array reference (the first title element under channel) f.

tagData – object method reference – tells the program to get the tagData for the title element g.

Some other possible uses: i.

$parser->document->channel[0]->item[$i] – when used in a for() loop, would get each item[$i] and allow you to do things with it.

XML Simple functions – PHP 5 (ISIS)

Note that the DOMXML functions are deprecated and are not implemented in PHP 5. PHP 5 uses a much simpler XML dom function called SimpleXML - http://us2.php.net/simplexml . This approach is much simpler as the document object is broken into an object for us.

<?php

$xml = new SimpleXMLElement ( “http://urlforxml.xml” );

//Simply loop through the XML file object and output tag values foreach ( $xml -> rss as $rss ) {

echo $rss -> channel->item->title , '<br />' ;

}

?>

Example 1 template pages

Main template page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title> RSS Feed Aggregator </title>

<link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" />

INLS572

2008

Spring 16

<meta name="DC.title" content="Sample XHTML Page"/>

<meta name="DC.author" content="Erik Mitchell"/>

<link rel="stylesheet" type="text/css" href="./class7_ex.css"/>

</head>

<body id="body_rss">

<div id="header">

</div>

<h1>RSS aggregation service</h1>

<div id="nav"><?php include('./site_nav.php')?></div>

<div id="main">

<h2>RSS Feed Aggregator</h2>

<?php

//Page Content

?>

</div>

</body>

</html>

Site navigation page

<?php echo <<<nav nav;

?>

<ul>

</ul>

<li id="nav_hom"><a href="/">Home</a></li>

<li id="nav_rss"><a href="/maps/">Subscribed RSS Feeds</a></li>

<li id="nav_jou"><a href="/journal/">Aggregated RSS Feeds</a></li>

<li id="nav_his"><a href="/history/">Place Holder</a></li>

<li id="nav_ref"><a href="/references/">Place Holder</a></li>

<li id="nav_con"><a href="/contact/">Place Holder</a></li>

External CSS File

/*INLS572 External CSS File */

*{margin:0; padding:0;} html {

font: small/1.4 "Lucida Grande", Tahoma, sans-serif;

} body {

font-size: 92%;

} a {text-decoration: none;

…..Lots more Content…..

INLS572

2008

Spring 17

Download