Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP with XML & AJAX XML: Extensible Markup Language AJAX: Asynchronous JavaScript and XML.

Similar presentations


Presentation on theme: "PHP with XML & AJAX XML: Extensible Markup Language AJAX: Asynchronous JavaScript and XML."— Presentation transcript:

1 PHP with XML & AJAX XML: Extensible Markup Language AJAX: Asynchronous JavaScript and XML

2 XML XML XML is used to describe and to focus on what data is. Describes the structure of the data XML was designed to transport and store data HTML was designed to display data XML must be parsed into html

3 Parsers Expat: Event based parser Views XML as a series of events, when a specific event occurs it will call a function DOM: Tree based parser Transforms an xml document into a tree structure, and provides access to tree elements

4 1 st, a little XML Tove Jani Reminder Don't forget me this weekend!

5 EXPAT "; break; case "TO": echo "To: "; break; case "FROM": echo "From: "; break; case "HEADING": echo "Heading: "; break; case "BODY": echo "Message: "; } } //Function to use at the end of an element function stop($parser,$element_name) { echo " "; } //Function to use when finding character data function char($parser,$data) { echo $data; } //Specify element handler xml_set_element_handler($parser,"start","stop"); //Specify data handler xml_set_character_data_handler($parser,"char"); //Open XML file $fp=fopen("test.xml","r"); //Read data while ($data=fread($fp,4096)) { xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); } //Free the XML parser xml_parser_free($parser); ?>

6 What it does… Initialize the XML parser with the xml_parser_create() function Create functions to use with the different event handlers Add the xml_set_element_handler() function to specify which function will be executed when the parser encounters the opening and closing tags Add the xml_set_character_data_handler() function to specify which function will execute when the parser encounters character data Parse the file "test.xml" with the xml_parse() function In case of an error, add xml_error_string() function to convert an XML error to a textual description Call the xml_parser_free() function to release the memory allocated with the xml_parser_create() function

7 DOM load("note.xml"); print $xmlDoc->saveXML(); foreach ($x->childNodes AS $item) { print $item->nodeName. " = ". $item->nodeValue. " "; } ?> Tove Jani Reminder Don't forget me this weekend!

8 Output #text = to = Tove #text = from = Jani #text = heading = Reminder #text = body = Don't forget me this weekend! #text = When XML generates, it often contains white-spaces between the nodes. The XML DOM parser treats these as ordinary elements, and if you are not aware of them, they sometimes cause problems.

9 Simple XML New with PHP 5 Easy way of accessing XML element’s attributes Elements are converted and sorted in arrays if there is more than one element on one level. Attributes are stored in an array, index corresponds to name Elements data is converted into strings.

10 Example Tove Jani Reminder Don't forget me this weekend! getName(). " "; foreach($xml->children() as $child) { echo $child->getName(). ": ". $child. " "; } ?> note to: Tove from: Jani heading: Reminder body: Don't forget me this weekend!

11 The AJAX Technique

12 The JavaScript function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=x mlhttp.responseText; } } xmlhttp.open("GET","gethint.php?q="+str,true); xmlhttp.send(); } Start typing a name in the input field below: First name: Suggestions:

13 PHP side <?php // Fill up array with names $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; $a[]="Liza"; $a[]="Elizabeth"; $a[]="Ellen"; $a[]="Wenche"; $a[]="Vicky"; //get the q parameter from URL $q=$_GET["q"]; //lookup all hints from array if length of q>0 if (strlen($q) > 0) { $hint=""; for($i=0; $i

14 MySQL and AJAX function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlh ttp.responseText; } } xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send(); } Check if a person is selected Create an XMLHttpRequest object Create the function to be executed when the server response is ready Send the request off to a file on the server Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

15 And then… PHP & MySQL Firstname Lastname Age Hometown Job "; while($row = mysql_fetch_array($result)) { echo " "; echo " ". $row['FirstName']. " "; echo " ". $row['LastName']. " "; echo " ". $row['Age']. " "; echo " ". $row['Hometown']. " "; echo " ". $row['Job']. " "; echo " "; } echo " "; mysql_close($con); ?> PHP opens a connection to a MySQL server The correct person is found An HTML table is created, filled with data, and sent back to the "txtHint" placeholder

16 PHP & Reading from XML files Same old Javascript load("cd_catalog.xml"); $x=$xmlDoc->getElementsByTagName('ARTIST'); for ($i=0; $i length-1; $i++) { //Process only element nodes if ($x->item($i)->nodeType==1) { if ($x->item($i)->childNodes->item(0)->nodeValue == $q) { $y=($x->item($i)->parentNode); } } } $cd=($y->childNodes); for ($i=0;$i length;$i++) { //Process only element nodes if ($cd->item($i)->nodeType==1) { echo(" ". $cd->item($i)->nodeName. ": "); echo($cd->item($i)->childNodes->item(0)->nodeValue); echo(" "); } } ?> PHP creates an XML DOM object Find all elements that matches the name sent from the JavaScript Output the album information (send to the "txtHint" placeholder)

17 Live Search - Links load("links.xml"); $x=$xmlDoc->getElementsByTagName('link'); //get the q parameter from URL $q=$_GET["q"]; //lookup all links from the xml file if length of q>0 if (strlen($q)>0) { $hint=""; for($i=0; $i length); $i++) { $y=$x->item($i)->getElementsByTagName('title'); $z=$x->item($i)->getElementsByTagName('url'); if ($y->item(0)->nodeType==1) { //find a link matching the search text if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) { if ($hint=="") { $hint=" item(0)->childNodes->item(0)->nodeValue. "' target='_blank'>". $y->item(0)->childNodes->item(0)->nodeValue. " "; } else { $hint=$hint. " item(0)->childNodes->item(0)->nodeValue. "' target='_blank'>". $y->item(0)->childNodes->item(0)->nodeValue. " "; } } } } } // Set output to "no suggestion" if no hint were found // or to the correct values if ($hint=="") { $response="no suggestion"; } else { $response=$hint; } //output the response echo $response; ?> Load an XML file into a new XML DOM object Loop through all elements to find matches from the text sent from the JavaScript Sets the correct url and title in the "$response" variable. If more than one match is found, all matches are added to the variable If no matches are found, the $response variable is set to "no suggestion"

18 RSS Feeds load($xml); //get elements from " " $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; //output elements from " " echo(" ". $channel_title. " "); echo(" "); echo($channel_desc. " "); //get and output " " elements $x=$xmlDoc->getElementsByTagName('item'); for ($i=0; $i 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; echo (" ". $item_title. " "); echo (" "); echo ($item_desc. " "); } ?> Load an XML file into a new XML DOM object Loop through all elements to find matches from the text sent from the JavaScript Sets the correct url and title in the "$response" variable. If more than one match is found, all matches are added to the variable If no matches are found, the $response variable is set to "no suggestion"

19 AJAX & Polling <?php $vote = $_REQUEST['vote']; //get content of textfile $filename = "poll_result.txt"; $content = file($filename); //put content in array $array = explode("||", $content[0]); $yes = $array[0]; $no = $array[1]; if ($vote == 0) { $yes = $yes + 1; } if ($vote == 1) { $no = $no + 1; } //insert votes to txt file $insertvote = $yes."||".$no; $fp = fopen($filename,"w"); fputs($fp,$insertvote); fclose($fp); ?> Result: Yes: ' height='20'> % No: ' height='20'> % Get the content of the "poll_result.txt" file Put the content of the file in variables and add one to the selected variable Write the result to the "poll_result.txt" file Output a graphical representation of the poll result


Download ppt "PHP with XML & AJAX XML: Extensible Markup Language AJAX: Asynchronous JavaScript and XML."

Similar presentations


Ads by Google