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 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. 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..
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 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); $leaf->appendChild($dom->createTextNode($v)); $item->appendChild($leaf); }
$inl = $dom->getElementsByTagName('forum')->item(0); $ref_node = $dom->getElementsByTagName('item')->item(1); $inl->insertBefore($item, $ref_node); $dom->save("new_xml.xml");
XML 24 GGeneneraeratteded XMLXML
XML 25 XML-RXML-RPPCC
XML-RPCXML-RPC aallowllowss aa comcompuputterer ttoo executexecutee fufunctnctionsions aandnd claclassss mmetethodhodss onon aanotnotherher comcompuputterer wwitithh aanyny ggiveniven aargrguummentents.s.
UsesUses HTTPHTTP forfor ttraransportnsportinging reqrequuestestss tthahatt aarere encodencodeded uusingsing XMLXML..
XML 26 XMLRXMLRPPCC RReqequuesestt
XML 27 XMLRXMLRPPCC RResesppononssee
XML 28 XMLRXMLRPPCC ServerServer
XML 29 RResesppononssee FFormormaattttiningg OpOpttionionss
verbosity: determine compactness of generated xml. options are no_white_space, newlines_only,, and pretty.. defaultfault = pretty
esccaping: determine how/whether to escape certain characters. 1 oror more values are allowed.. If multiple,, they need to be specified as a sub-array.. options are:: cdata, non-ascii, non-print, and markup.. defaultfault = non-ascii, non-print,, markup
version: version of xml vocabulary to use.. currently,, three are supported:: xmlrpc,, soap 1.1,, and simple.. defaultfault = xmlrpc
encodingoding: the encoding that the data is in. defaultfault = iso-8859-1
XML 30 XMLRXMLRPPCC CCllienientt
$req = xmlrpc_encode_request("date", array());
$opts = array( 'http'=>array( 'method' => "POST", 'content' => $req ) );
$context = stream_context_create($opts); $ctx = @file_get_contents( "http://localhost/xmlrpc_server.php", NULL, $context); echo xmlrpc_decode($ctx);
XML 31 PProsros && CCononss
EaEasysy ttoo uundndersterstaandnd,, NNoo neneww fufunctnctionionalityality imimplemplementent aandnd beingbeing aadddded.ed. ddebuebugg.. NNotot cocommpplletetelelyy QQuuititee fafastst.. buzbuzzwzwordord cocompmplilianantt.. SSttaableble VerVeryy ffeeww bbiigg CCaann bebe ememuulalatteded wwitithh proprovividdersers ususee PEARPEAR XXMMLRLRPPCC..
XML 32 SOASOAPP
FormFormerlyerly knowknownn aass SSimimpleple OObjectbject AAccessccess ProtProtocol.ocol. AA mmessaessagginging formformaatt primprimaaryry uusedsed forfor RRPCPC.. UsesUses XMXMLL.. VViewiew SSouourcerce protprotocol.ocol. DDevelopedeveloped jointjointlyly byby MMicrosofticrosoft,, IIBMBM aandnd W3CW3C..
XML 33 SOASOAPP RRuulleses
EaEachch SOAPSOAP ddocuocumementnt,, bbee iitt aa rreqequuestest oorr responseresponse mmuustst followfollow aa setset ofof formformaattttinging rurules:les:
MMuustst havhavee aa top-ltop-leevveell EnvEnveellopeope namenamespacspaceedd toto http://schttp://schehemas.xmlmas.xmlsoap.orgsoap.org/soap/e/soap/envnveellopeope// MMuustst ccontaiontainn BBodyody eelleemement.nt. MMayay ccontaiontainn anan optioptionalonal HHeeadeaderr andand FFauaulltt eelleemements.nts. TThehe cconteontentsnts ofof HHeeadeaderr andand BBodyody mumustst bebe propeproperlrlyy namenamespacspaceed.d.
XML 34 SSOOAAPP DDocuocummenentt
XML 35 SOASOAPP FFaauullttss
FaFauultltss cacann bebe ofof foufourr babasicsic ttypes:ypes: VersionMismatch: invalid namespace for the SOAP Envelopelope MustUnderstand: a required header was not understood by the server Client: the message sent by the client was not properly formed,, or did not contain the necessary information to fulfill the request.. Server: the message could not be prococessed
FFauaulltsts ccanan alalsoso ccontaiontainn otheotherr iinfnformatiormation,on, susucchh asas aa basibasicc memessagssagee dedescscriribibingng thethe ffauaullt,t, thethe UURIRI ofof thethe orioriggiinatornator ofof thethe ffauaullt,t, andand aa dedetaitaill ffiieelldd thatthat ccanan bebe uusesedd toto provproviidede anyany otheotherr data.data.
XML 36 SOASOAPP FFaauulltt
XML 37 SOASOAPP CCllienientt
doGetCachedPage($developer_id, "http://ilia.ws"); // display retrieved page echo base64_decode($google_cache); ?>
XML 38 WWeebb SeSerrvvicicee DDeescrscriptioiptionn LaLangnguuagagee
WSDLWSDL isis mmaachinechine reareaddaableble ddescriptescriptionion ((XMLXML)) ofof aa wwebeb service.service. TThehe seservrviiccee provproviidederr uusesess WSDLWSDL toto dedescscriribebe thethe memethodsthods ofofffeers,rs, thetheiirr parameparametetersrs andand thethe reretuturnrn vvalaluueess thethe cclliieentnt maymay eexpexpecct.t. TThehe cclliieentnt parseparsess thethe WSWSDDLL toto dedetetermirminene thethe avavaiaillablablee memethods,thods, howhow toto eencncodeode thethe parameparametetersrs toto thethemm andand howhow toto dedealal wwiithth thethe reretuturnernedd data.data.
XML 39 CCaappttcchaha WWSDSDLL
XML 40 CCaappttcchaha WWSDSDLL
XML 41 CCaappttcchaha WWSDSDLL
AAss youyou cacann seesee ttoo providprovidee aa veryvery simsimpleple wwebeb services,services, onlyonly offeringoffering ttwwoo fufunctnctionsions ttaakeskes severaseverall papaggeses ofof WDSLWDSL wwebeb serviceservice ddescriptescription.ion.
XML 43 ServerServer CCododee
// instantiate SOAP server $server = new SoapServer("./captcha.wsdl"); // Register exposed method $server->addFunction('captcha'); // generate captcha $server->addFunction('check_captcha'); // check captcha ID $server->handle(); // listen of requests via POST
AsAs ffarar asas thethe PPHHPP iimplmpleemementatintationon ggoeoes,s, thethe neneeedededd ccodeode iiss eextrextrememellyy sisimplmplee,, iinn manymany wwayayss makmakiingng uupp fforor thethe ccomplompleexixititieess ofof WSDLWSDL..
XML 44 CClliienentt InIntteerrfafacece
check_captcha($_POST['text'], $_POST['id'])) echo Validation Passed
'; else echo 'Validation Failed
'; } ?>
XML 45 >
XML 46 QuQuesesttionionss
XML 47