Web Services In

Web Services In

WeWebb SeServirvicceess iinn PPHHPP By:By: IIlialia AAlshalshanetnetskysky ThThee RREESTST WWaayy ReReprepresesentatintationalonal StateState TTransfransfeerr (REST(REST)) ConcConceeptpt ccoineoinedd byby Roy FFieielding UUsesess thethe wweebb oror toto bebe preprecciisese HHTTTTPP oror HHTTTTPPSS eexcxclluusisivvee fforor transmitransmittittingng wweebb seservrviiccee rereqquueestst andand reresponsesponse.. CCllassiassicc sesetutup:p: InputInput viavia GEGET/PT/POOST OOututputput aass XXMMLL docdocumeumentnt XML 2 RREESTST RReqequuesestt http://site.com/forum/rss.php?latest=1 TThahatt’’ss aallll ffololkkss WaWantnt ttoo mamakkee aa rremotemotee rrequestequest?? NoNo prprobloblem!em! $ur$urll == ““……””;; $r$responseesponse == ffilile_e_ggetet__contcontentents(s($ur$urll));; XML 3 RREESTST RResesppononssee <?xml version="1.0"?> <forum uri="http://fudforum.org/index.php"> <item id="1"> <title>First Post!!!</title> <link>http://fudforum.org/index.php/m/1</link> <description>1st message in the forum.</description> </item> <item id="2"> <title>Re: First Post!!!</title> <link>http://fudforum.org/index.php/m/1</link> <description>Almost like Slashdot.</description> </item> </forum> XML 4 PPaarsrsiningg XMLXML RResesppononssee TToo parseparse thethe reretuturnernedd XMXMLL wwee tuturnrn toto anyany nunumbemberr ofof eextextensinsionsons ffououndnd iinn PPHHPP.. XXMMLL eexxtteensionnsion Basic XML parser based on SAX methodology found in all PHP versions. SimpleSimpleXXMML Arguably the simplest XML parser to use.. DODOMM Maximum flexibility for both parsing and creating XML XXMMLLReReaadederr Pull parser,, that combines ease of use with high performance.. XML 5 XMLXML PPaarsrsiningg MetMethhododolologogiesies SAXSAX DDOMOM (Simple API for XML) (Document Object Model) AnAn eevveentnt basebasedd approacapproachh LLoadsoads thethe eentintirere docdocuumementnt wwheherere byby eeacachh acactition,on, susucchh iintonto mememorymory,, ccrereatiatingng aa ““ffououndnd neneww tagtag”” neneeedsds toto ““tretreee”” rereprepressentientingng tthhee bebe handlhandleed.d. TThehe tritriggggeerablrablee XMXMLL data.data. TThehe tretreee ccanan eevveentsnts iincnclluudede:: thethenn bebe travtraveersersedd iinn open tag mumulltititutudede ofof wwayays.s. close tag tag’s data XML 6 SiSimpmplele APAPII ffoorr XXMLML UUsesess lliittlttlee mememorymory.. AlAlll tthoshosee hhandandlleerr calcallsls AlAlllowowss wworkork toto aarere sslowlow.. startsstarts iimmemmedidiateatellyy.. OOnlynly SeSeqqueuentntiiaall ddataata WWorkorkss wweellll wwiithth reremotemote aaccccess.ess. XMXMLL datadata sousourcrcee.. CCanan’t’t eeaassililyy rreettrrieieveve aa SameSame parsiparsingng APAPII iinn parparttiicucullaarr ddooccuumentment PPHHPP 44 andand 55 sesegmegmentnt.. ReReqquiuiresres lotlot’s’s ofof PPHHPP ccooddee.. ReReadad-o-onlnlyy.. XML 7 DDooccuumemenntt OObbjejecctt MoModdeell VeVeryry ffastast fforor smalsmalll ““AlAlll youyourr memomemoryry araree docdocuumements.nts. bebelonlongg toto DOMDOM””.. AcAccceessss anyanythithingng anyanytitimeme.. DaDattaa ononlyly uusablesable afafterter SiSimplmpleerr PPHHPP iintenterfrfacacee.. thethe ccompomplleteete ddooccuumentment iiss rerettrriieevveedd ppararsesed.d. UUndenderlrlyyiingng XMXMLL parsiparsingng lliibrarybrary,, lliibXMbXMLL22 iiss YoYou’lu’lll nneeeedd PPHHPP 55++.. bebettetterr susuiitetedd fforor DODOMM.. XML 8 PPHPHP’’ss XMLXML PPaarsrsererss SAXSAX DDOMOM (Simple API for XML) (Document Object Model) XMXMLL SSimpimpleleXMLXML XMXMLLReReadeaderr (P(PECECLL)) DODOMM (PH(PHPP55)) XMXMLLWWririteterr (P(PECECLL)) DODOMXMMXMLL ((PHPHPP 4)4) XSXSLLTT (d(doomm eenngginine)e) SSOAOAPP ((ddomom eenngiginene)) XMXMLL-RPC-RPC (d(doomm eenngginine)e) XML 9 BBigigggesestt GGripripee AAbbououtt SaSaxx OOnene ofof tthehe bigbigggestest comcomplaplaintintss aabouboutt SSAAXX isis tthahatt itit PHPHPP reqrequuiresires tthehe ddevelopereveloper ttoo wwritritee aa lotlot ofof codcodee aandnd bebe fufullylly aawwaarere ofof tthehe XMXMLL beingbeing paparsedrsed.. XML 10 ItIt cacann’’tt bbee tthhaatt bbaadd,, cacann itit?? class xmlParser { private $x, $file, $cur_tag, $cur_id; public $data_store = array(), $n_entries = 0; function __construct($xml_file) { $this->file = $xml_file; $this->x = xml_parser_create(); xml_set_object($this->x, $this); xml_set_element_handler($this->x, "startTag", "endTag"); xml_set_character_data_handler($this->x, ‘tagContent'); } function parse() { $fp = fopen($this->file, "r"); while (!feof($fp)) xml_parse($this->x, fread($fp, 1024), feof($fp)); fclose($fp); } function __destruct() { xml_parser_free($this->x); } XML 11 CCaallllbbaackckss function startTag($parser, $tag_name, $attribute) { if ($tag_name == 'ITEM') { $this->cur_id = (int)$attribute['ID']; $this->data_store[$this->cur_id] = array(); } else if ($tag_name != 'FORUM') $this->data_store[$this->cur_id][$tag_name] = ''; $this->cur_tag = $tag_name; } function endTag($parser, $tag_name) { if ($tag_name == 'ITEM') ++$this->n_entries; } function tagContent($parser, $data) { if (in_array($this->cur_tag, array ('TITLE','LINK','DESCRIPTION'))) $this->data_store[$this->cur_id][$this->cur_tag] .= $data; } XML 12 CCaassee SenSenssititivitivityy OOnene ofof tthinghingss XMXMLL shasharesres wwitithh HHTMTMLL isis tthehe inherentinherent cacase-se-insensitinsensitivitivityy ofof tthehe ttaaggs.s. TheThe XMXMLL extextensionsensions aauuttomomaatticaicallylly ““solves”solves” tthishis problemproblem forfor youyou byby cacase-se-foldfoldinging aallll ttaaggss ttoo uuppercappercase.se. TToo didisablsablee thithiss ffuuncnctitionalonaliityty uusese:: xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); XML 13 WWhhyy hhaaveve ppaarsrserer inin hhaannddllersers?? TheThe paparserrser referencereference aallowllowss retretrievarievall aaddddititionaionall informinformaattionion aabouboutt tthehe XMXMLL contcontentent.. xml_get_current_line_number(resource parser) The current line number in the XML file.. xml_get_current_byte_index(resource parser) The current file position (starts at 0).. xml_get_current_column_number(resource parser) The positionion inin tthe current column (startts at 0).. XML 14 WWhhaatt AAbbououtt EErrorsrrors?? IInn tthehe eventevent ofof aann errorerror xml_parse()xml_parse() wwillill retretuurnrn 0.0. function parse() { $fp = fopen($this->file, "r"); while (!feof($fp)) { if (!xml_parse($this->x, fread($fp, 1024), feof($fp))) { printf("Error #%d: '%s' on %s:%d\n", ($c = xml_get_error_code($this->x)), xml_error_string($c), $this->file, xml_get_current_line_number($this->x)); } } fclose($fp); } XML 15 PPuuttttiningg itit aallll ttogogetethherer $a = new xmlParser("xml.xml"); $a->parse(); echo "Found {$a->n_entries} Messages\n"; foreach ($a->data_store as $id => $v) { echo "{$id}) {$v['TITLE']}\n"; } OOutput:utput: Messages Found: 2 1) First Post!!! 2) Re: First Post!!! XML 16 SimSimpplleXMLeXML ttoo tthhee RResescucue!e! ThaThanksnks ttoo tthehe SimpleXMLSimpleXML extextension,ension, itit cacan.n. <?php foreach (simplexml_load_file("xml.xml") as $v) { echo "{$v['id']}) '{$v->title}'\n"; } ?> ByBy mmaakingking uusese ofof tthehe newnew PHPHPP 55 OOOO feafeattuuresres susuchch aass __toString()__toString() aandnd objectobject overloaoverloaddinging itit mmaakeskes paparsingrsing XMXMLL soso veryvery simsimple.ple. XML 17 DDOMOM EExxttenenssionion DOMDOM extextensionension isis aa comcompletpletee rewrewritritee ofof tthehe DOMXMLDOMXML extextensionension tthahatt wwaass aavavailailableble inin PHPPHP 4.4. TheThe corecore fufunctnctionaionalitlityy incluincluddes:es: ReRead/Wad/Wriritete/C/Crereateate ffuuncnctitionalonaliityty.. XPXPathath qquueeririees.s. SeSevveeralral docdocuumementnt vvalaliidatidationon memecchanihanisms.sms. NameNamespacspacee SuSupportpport HHTTMMLL parsiparsingng ccapabiapabilliititiees.s. XML 18 BBaassicic UUssaaggee ReReadiadingng datadata ffromrom XMLXML docdocuumementnt vviiaa DOMDOM iiss cconconceeptuptualalllyy notnot mumucchh didiffffeererentnt ffromrom SimpleXMLSimpleXML.. <?php $dom = new domDocument(); $dom->load("xml.xml"); foreach ($dom->getElementsByTagName('title') as $k => $node) { $id = $dom->getElementsByTagName('item')-> item($k)->getAttribute('id'); echo "{$id}) {$node->nodeValue}\n"; } ?> XML 19 CCreareattiningg XMLXML $dom = new domDocument("1.0","ISO-8859-1"); $dom->formatOutput = 1; $root = $dom->createElement('books'); $branch = $dom->createElement('book'); $branch->setAttribute('ISBN', '0973862106'); $leaf = $dom->createElement('title'); $leaf->appendChild( $dom->createTextNode(‘PHP Guide to Security')); $branch->appendChild($leaf); XML 20 CCrreateatinging XXMMLL SSteptep 22 $leaf = $dom->createElement('price'); $leaf->appendChild( $dom->createTextNode('32.99')); $branch->appendChild($leaf); $leaf = $dom->createElement('url'); $leaf->appendChild( $dom->createCDATASection(‘amazon.com/…’); $branch->appendChild($leaf); XML 21 CCrreateatinging XXMMLL SSteptep 33 $root->appendChild($branch); $dom->appendChild($root); echo $dom->saveXML(); XML 22 WWhhaatt ddoo wwee hhaave?ve? <?xml version="1.0" encoding="ISO-8859-1"?> <books> <book ISBN="0596007647"> <title>PHP Guide to Security</title> <price>26.37</price> <url><![CDATA[amazon.com/...]]></url> </book> </books> XML 23 ModModifyinifyingg EExxisisttiningg DDocuocummenenttss $dom = new domDocument(); $dom->load("xml.xml"); $item = $dom->createElement('item'); $item->setAttribute('id', '1.5'); foreach (array('title', 'link','description') as $v) { $leaf = $dom->createElement($v);

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    47 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us