CopyrightIBMCorporation2007TrademarksXMLforPHPdevelopers,Part3:Advancedtechniquestoread,manipulate,andwriteXMLPage1of9XMLforPHPdevelopers,Part3:Advancedtechniquestoread,manipulate,andwriteXMLAddXSLTtoDOMandSimpleXMLAPIsCliffMorganMarch13,2007Thisfinalarticleinathree-partseriesdiscussesmoretechniquesforreading,manipulating,andwritingXMLinPHP5.
Init,youwillfocusonthenowfamiliarAPIsDOMandSimpleXMLinmoresophisticatedsurroundings,and,forthefirsttimeinthisthree-partseries,ontheXSLextension.
ViewmorecontentinthisseriesIntroductionPHP5offersthedeveloperalotmoremuscletoworkwithXML.
NewandmodifiedextensionssuchastheDOM,SimpleXML,andXSLmakeworkingwithXMLlesscodeintensive.
InPHP5,theDOMiscompliantwiththeW3Cstandard.
Mostimportantly,theinteroperabilityamongtheseextensionsissignificant,providingadditionalfunctionality,likeswappingformatstoextendusability,W3C'sXPath,andmore,acrosstheboard.
Hereyouwilllookatinputandoutputoptions,andyouwilldependontheYahooWebServicesRESTprotocolinterfacetoprovideamoresophisticatedshowcaseforthefunctionalityofthenowfamiliarDOMandSimpleXMLextensionsandconcludewiththeXSLextension.
PreviouslyinthisseriesOtherarticlesinthisseriesXMLforPHPdevelopers,Part1:The15-minutePHP-with-XMLstarterXMLforPHPdevelopers,Part2:AdvancedXMLparsingtechniquesThefirstarticleofthisseriesprovidedessentialinformationonXML.
ItfocusedonquickstartApplicationProgrammingInterfaces(APIs)anddemonstratedhowSimpleXML,whencombinedwiththeDocumentObjectModel(DOM)asnecessary,istheidealchoiceforifyouworkwithstraightforward,predictable,andrelativelybasicXMLdocuments.
Part2lookedatthebreadthofparsingAPIsavailableforXMLinPHP5,includingSimpleXML,theDOM,SimpleAPIforXML(SAX),andXMLReaderandconsideredwhichparsingtechniquesweremostappropriatefordifferentsizesandcomplexitiesofXMLdocuments.
developerWorksibm.
com/developerWorks/XMLforPHPdevelopers,Part3:Advancedtechniquestoread,manipulate,andwriteXMLPage2of9XMLinPHP5ExtensibleMarkupLanguage(XML),describedasbothamarkuplanguageandatext-baseddatastorageformat,offersatext-basedmeanstoapplyanddescribeatree-basedstructuretoinformation.
Hereyou'lllookatXMLinthecontextofWebservices,probablyoneofthemostimportantfactorsdrivingtherecentgrowthofXMLoutsidetheenterpriseworld.
InPHP5,therearetotallynewandentirelyrewrittenextensionsformanipulatingXML,allbasedonthesamelibxml2code.
Thiscommonbaseprovidesinteroperabilitybetweentheseextensionsthatextendsthefunctionalityofeach.
Thetree-basedparsersincludeSimpleXML,theDOM,andtheXSLTprocessor.
IfyouarefamiliarwiththeDOMfromotherlanguages,youwillhaveaneasiertimecodingwithsimilarfunctionalityinPHPthanbefore.
Thestream-basedparsersincludetheSimpleAPIforXML(SAX)andXMLReader.
SAXfunctionsthesamewayitdidinPHP4.
ManipulatingXMLusingtheDOMYoucanusetomanipulateanXMLfile.
UsingtheDOMisefficientonlywhentheXMLfileisrelativelysmall.
TheadvantagestousingthismethodarethesolidstandardofthefamiliarW3CDOM,itsmethods,andtheflexibilityitbringstocoding.
ThedisadvantagesoftheDOMarethedifficultyincodingandperformanceissueswithlargedocuments.
TheDOMinactionWiththeDOM,youcanbuild,modify,query,validateandtransformXMLdocuments.
AllDOMmethodsandpropertiescanbeused,andmostDOMlevel2methodsareimplementedwithpropertiesproperlysupported.
DocumentsparsedwiththeDOMcanbeascomplexastheycomethankstoitstremendousflexibility.
Rememberhowever,thatflexibilitycomesatapriceifyouloadalargeXMLdocumentintomemoryallatonce.
TheexamplesinthisarticleuseYahoo'ssearchAPI,PHP5,andREpresentationalStateTransfer(REST)toillustratetheuseoftheDOMinaninterestingapplicationenvironment.
YahoochoseRESTbecauseofacommonbeliefamongdevelopersthatRESToffers80%ofSOAP'sbenefitsat20%ofthecost.
IchosethisapplicationtoshowcasePHP/XMLbecausethepopularityofWebservicesisprobablyoneofthemostimportantfactorsdrivingtherecentgrowthofXMLoutsidetheenterpriseworld.
Typically,RESTformsarequestbybeginningwithaserviceentryURLandthenappendingsearchparametersintheformofaquerystring.
ThenListing1parsestheresultsofthequeryusingtheDOMextension.
Listing1.
TheYahooDemocodesampleusingtheDOMfirstChild;//Next,loopthrougheachofitsattributesforeach($root->attributesas$attr){$res[$attr->name]=$attr->value;}//Now,loopthrougheachofthechildrenoftherootelement//andtreateachappropriately.
//Startwiththefirstchildnode.
(Thecounter,i,isfor//trackingresults.
$node=$root->firstChild;$i=0;//Nowkeeploopingthroughaslongasthereisanodetowork//with.
(Atthebottomoftheloop,thecodemovestothenext//sibling,sowhenitrunsoutofsiblings,theroutinestops.
while($node){//Foreachnode,checktoseewhetherit'saResultelementor//oneoftheinformationalelementsatthestartofthedocument.
switch($node->nodeName){//Resultelementsneedmoreanalysis.
case'Result'://AddeachchildnodeoftheResulttotheresultobject,//againstartingwiththefirstchild.
$subnode=$node->firstChild;while($subnode){//Someofthesenodesjustarejustwhitespace,whichdoes//nothavechildren.
if($subnode->hasChildNodes()){//Ifitdoeshavechildren,getaNodeListofthem,and//loopthroughit.
$subnodes=$subnode->childNodes;foreach($subnodesas$n){//Againcheckforchildren,addingthemdirectlyor//indirectlyasappropriate.
if($n->hasChildNodes()){foreach($n->childNodesas$cn){$res[$i][$subnode->nodeName][$n->nodeName]=trim($cn->nodeValue);}}else{$res[$i][$subnode->nodeName]=trim($n->nodeValue);}}}//Moveontothenextsubnode.
$subnode=$subnode->nextSibling;}$i++;break;//Otherelementsarejustaddedtotheresultobject.
default:$res[$node->nodeName]=trim($node->nodeValue);developerWorksibm.
com/developerWorks/XMLforPHPdevelopers,Part3:Advancedtechniquestoread,manipulate,andwriteXMLPage4of9break;}//MoveontothenextResultofinformationalelement$node=$node->nextSibling;}return$res;}//First,converttheXMLtoaDOMobjectyoucanmanipulate.
$res=xml_to_result($dom);//Useoneofthose"informational"elementstodisplaythetotal//numberofresultsforthequery.
echo"Thequeryreturns".
$res["totalResultsAvailable"].
"totalresultsThefirst10areasfollows:";//Nowloopthrougheachoftheactualresults.
for($i=0;$i".
$res[$i]['Title'].
":";echo$res[$i]['Summary'];echo"";}>ManipulatingXMLusingSimpleXMLTheSimpleXMLextensionisatoolofchoiceformanipulatinganXMLdocument,providedthattheXMLdocumentisn'ttoocomplicatedortoodeep,andcontainsnomixedcontent.
SimpleXMLiseasiertocodethantheDOM,asitsnameimplies.
Itisfarmoreintuitiveifyouworkwithaknowndocumentstructure.
GreatlyincreasingtheflexibilityoftheDOMandSimpleXMLtheinteroperativenatureofthelibXML2architectureallowsimportstoswapformatsfromDOMtoSimpleXMLandbackatwill.
SimpleXMLinactionDocumentsmanipulatedwithSimpleXMLsimpleandquicktocode.
ThefollowingcodeparsestheresultsofthequeryusingtheSimpleXMLextension.
Asyoumightexpect,thefollowingSimpleXMLcode(seeListing2)ismorecompactthantheDOMcodeexampleshownaboveinListing1.
Listing2.
TheYahooSimpleXMLexampleattributes()as$name=>$attr){$res[$name]=$attr;}ibm.
com/developerWorks/developerWorksXMLforPHPdevelopers,Part3:Advancedtechniquestoread,manipulate,andwriteXMLPage5of9//Useoneofthose"informational"elementstodisplaythetotal//numberofresultsforthequery.
echo"Thequeryreturns".
$res["totalResultsAvailable"].
"totalresultsThefirst10areasfollows:";//UnlikewithDOM,whereweloadedtheentiredocumentintothe//resultobject,withSimpleXML,wegetbackanobjectinthe//firstplace,sowecanjustusethenumberofresultsreturned//toloopthroughtheResultmembers.
for($i=0;$iResult[$i];echo"ClickUrl.
"'>".
$thisResult->Title.
":";echo$thisResult->Summary;echo"";}>Listing3addsacachelayertotheSimpleXMLexamplefromListing2.
Thecachecachestheresultsofanyparticularqueryfortwohours.
Listing3.
TheYahooSimpleXMLexamplewithacachelayer(time()-7200)){//Ifthere'savalidcachefile,loaditsdata.
$data=file_get_contents($cache);}else{//Ifthere'snovalidcachefile,grabaliveversionofthe//dataandsaveittoatemporaryfile.
Oncethefileiscomplete,//copyittoapermanentfile.
(Thispreventsconcurrencyissues.
)$data=file_get_contents($query);$tempName=tempnam('c:\temp','YWS');file_put_contents($tempName,$data);rename($tempName,$cache);}developerWorksibm.
com/developerWorks/XMLforPHPdevelopers,Part3:Advancedtechniquestoread,manipulate,andwriteXMLPage6of9//Whereverthedatacamefrom,loaditintoaSimpleXMLobject.
$xml=simplexml_load_string($data);//Fromhere,therestofthefileisthesame.
//Loaduptherootelementattributesforeach($xml->attributes()as$name=>$attr){$res[$name]=$attr;}.
.
.
ManipulatingXMLusingXSLEXtensibleStylesheetLanguage(XSL)isafunctionalXMLlanguagethatwascreatedforthetaskofmanipulatingXMLdocuments.
UsingXSL,youcantransformanXMLdocumentintoaredefinedXMLdocument,anXHTMLdocument,anHTMLdocument,oratextdocumentbasedonastylesheetdefinitionsimilartothewayCSSworksbyimplementingrules.
PHP5'simplementationoftheW3CstandardsupportsinteroperabilitywiththeDOMandXPath.
EXtensibleStylesheetLanguageTransformations(XSLT)isanXMLextensionbasedonlibxml2,anditsstylesheetsareXMLdocuments.
XSLTtransformsanXMLsourcetreeintoanXMLorXML-typeresulttree.
ThesetransformationsapplytheseriesofrulesspecifiedinthestylesheettotheXMLdata.
XSLTcanaddorremoveelementsorattributestoorfromtheoutputfile.
Itallowsthedevelopertosortorrearrangeelementsandmakedecisionsaboutwhatelementstohideordisplay.
DifferentstylesheetsallowforyourXMLtobedisplayedappropriatelyfordifferentmedia,suchasscreendisplayversusprintdisplay.
XSLTusesXPathtonavigatethroughtheoriginalXMLdocument.
TheXSLTtransformationmodelusuallyinvolvesasourceXMLfile,anXSLTfilecontainingoneormoreprocessingtemplates,andanXSLTprocessor.
XSLTdocumentshavetobeloadedusingtheDOM.
PHP5supportsonlythelibxsltprocessor.
XSLinactionAninterestingapplicationofXSListocreateXMLfilesontheflytocontainwhateverdatahasjustbeenselectedfromthedatabase.
Usingthistechnique,itispossibletocreatecompleteWebapplicationswherethePHPscriptsaremadeupofXMLfilesfromdatabasequeries,thenuseXSLtransformationstogeneratetheactualHTMLdocuments.
Thismethodcompletelysplitsthepresentationlayerfromthebusinesslayersothatyoucanmaintaineitheroftheselayersindependentlyoftheother.
Listing4illustratestherelationshipbetweentheXMLinputfile,theXSLstylesheet,theXSLTprocessor,andmultiplepossibleoutputs.
Listing4.
XMLtransformationload('recipe.
xsl');//Loadthestylesheetintotheprocessor$xslt->importStylesheet($xsl);//LoadXMLinputfile$xml=newDOMDocument();$xml->load('recipe.
xml');//Nowchooseanoutputmethodandtransformtoit://Transformtoastring$results=$xslt->transformToXML($xml);echo"Stringversion:";echohtmlentities($results);//TransformtoDOMobject$results=$xslt->transformToDoc($xml);echo"TherootoftheDOMDocumentis";echo$results->documentElement->nodeName;//Transformtoafile$results=$xslt->transformToURI($xml,'results.
txt');>SummaryTheearlierpartsofthisseriesfocusedontheuseoftheDocumentObjectModelandonSimpleXMLtoperformbothsimpleandcomplexparsingtasks.
Part2alsolookedattheuseofXMLReader,whichprovidesafastereasierwaytoperformtasksthatonewouldpreviouslydousingSAX.
Now,inthisarticle,yousawhowtoaccessremotefilessuchasREST-basedWebservices,andhowtouseXSLTtoeasilyoutputXMLdatatoastring,DOMDocumentobject,orfile.
developerWorksibm.
com/developerWorks/XMLforPHPdevelopers,Part3:Advancedtechniquestoread,manipulate,andwriteXMLPage8of9RelatedtopicsXMLforPHPdevelopers,Part1:The15-minutePHP-with-XMLstarter(CliffMorgan,developerWorks,February2007):Inthefirstarticleofthisthree-partseries,discoverPHP5'sXMLimplementationandhoweasyitistoworkwithXMLinaPHPenvironment.
XMLforPHPdevelopers,Part2:AdvancedXMLparsingtechniques(CliffMorgan,developerWorks,March2007):InPart2ofthisthree-partseries,exploreXMLparsingtechniquesinPHP5,andlearnhowtodecidewhichparsingmethodisbestforyourapp.
Tip:UseLanguagespecifictoolsforXMLprocessing(UcheOgbuji,developerWorks,January2004):TrythesealternativestoSAXandDOMwhenyouparseXML.
IntuitionandBinaryXML(LeighDodds,XML.
com,April2001):ReadaboutthedebateconcerningbinaryencodedalternativestoXML.
WhatkindoflanguageisXSLT(MichaelKay,developerWorks,April2005):PutXSLTincontextasyoulearnwherethelanguagecomesfrom,whatit'sgoodat,andwhyyoushoulduseit.
Tip:ImplementXMLReader:AninterfaceforXMLconverters(BenotMarchal,developerWorks,November2003):ExploreAPIsforXMLpipelines.
ReadingandwritingtheXMLDOMinPHP(JackHerrington,developerWorks,December2005):ExplorethreemethodstoreadXML:theDOMlibrary,theSAXparser,andregularexpressions.
Also,lookathowtowriteXMLusingDOMandPHPtexttemplating.
SimpleXMLProcessingwithPHP(ElliotteRustyHarold,developerWorks,October2006):TrytheSimpleXMLextensionandenableyourPHPpagestoquery,search,modify,andrepublishXML.
IntroducingSimpleXMLinPHP5(AlejandroGervasio,DevShed,June2006):Inthefirstofathree-partarticleseriesonSimpleXML,saveworkwiththebasicsofthesimplexmlextensioninPHP5,alibrarythatprimarilyfocusesonparsingsimpleXMLfiles.
PHPCookbook,SecondEdition(AdamTrachtenbergandDavidSklar,O'ReillyMedia,August2006):LearntobuilddynamicWebapplicationsthatworkonanyWebbrowser.
XML.
com:VisitO'Reilly'sXMLsiteforcomprehensivecoverageoftheXMLworld.
W3CXMLInformation:ReadtheXMLspecificationfromthesource.
PHPdevelopmenthomesite:Learnmoreaboutthiswidely-usedgeneral-purposescriptinglanguagethatisespeciallysuitedforWebdevelopment.
VisitPEAR:PHPExtensionandApplicationRepository:GetmoreinformationonPEAR,aframeworkanddistributionsystemforreusablePHPcomponents.
PECL:PHPExtensionCommunityLibrary:VisitthesistersitetoPEARandrepositoryforPHPExtensions.
PlanetPHP:VisitthePHPdevelopercommunitynewssource.
xmllib2:GetthetheXMLCparserandtoolkitofGnome.
IBMcertification:FindouthowyoucanbecomeanIBM-CertifiedDeveloper.
XMLtechnicallibrary:SeethedeveloperWorksXMLZoneforawiderangeoftechnicalarticlesandtips,tutorials,standards,andIBMRedbooks.
IBMtrialsoftware:BuildyournextdevelopmentprojectwithtrialsoftwareavailablefordownloaddirectlyfromdeveloperWorks.
ibm.
com/developerWorks/developerWorksXMLforPHPdevelopers,Part3:Advancedtechniquestoread,manipulate,andwriteXMLPage9of9CopyrightIBMCorporation2007(www.
ibm.
com/legal/copytrade.
shtml)Trademarks(www.
ibm.
com/developerworks/ibm/trademarks/)
DMIT怎么样?DMIT最近动作频繁,前几天刚刚上架了日本lite版VPS,正在酝酿上线日本高级网络VPS,又差不多在同一时间推出了美国cn2 gia线路不限流量的美国云服务器,不过价格太过昂贵。丐版只有30M带宽,月付179.99美元 !!目前,美国云服务器已经有个4个套餐,分别是,Premium(cn2 gia线路)、Lite(普通直连)、Premium Secure(带高防的cn2 gia线...
虎跃科技怎么样?虎跃科技(虎跃云)是一家成立于2017年的国内专业服务商,专业主营云服务器和独立服务器(物理机)高防机房有着高端华为T级清洗能力,目前产品地区有:山东,江苏,浙江等多地区云服务器和独立服务器,今天虎跃云给大家带来了优惠活动,为了更好的促销,枣庄高防BGP服务器最高配置16核32G仅需550元/月,有需要的小伙伴可以来看看哦!产品可以支持24H无条件退款(活动产品退款请以活动规则为准...
快云科技已稳步运行进两年了 期间没出现过线路不稳 客户不满意等一系列问题 本司资质齐全 持有IDC ICP ISP等正规手续 有独特的网站设计理念 在前几天刚是参加过魔方系统举行的设计大赛拿获最佳设计奖第一名 本公司主营产品 香港弹性云服务器,美国vps和日本vps,香港物理机,国内高防物理机以及美国日本高防物理机 2020年的国庆推出过一款香港的回馈用户特惠机 已作为传家宝 稳定运行 马上又到了...
file_get_contents为你推荐
中國信託商業銀行请务必阅读正文之后的免责条款部分http://www.huajinsc.cn/支持ipad支持ipadxp如何关闭445端口Windows XP 怎么关闭445端口,我是电脑小白,求各位讲详细点重庆电信宽带管家电信的宽带上网助手是什么?css选择器CSS中的选择器分几种?morphvoxpro教程哪位大佬可以帮忙调一下morphvox pro的女声啊,我调了一天还是没调明白morphvoxpro教程morphvox是什么 morphvox怎么使用 morphvox设置方法
企业域名备案 zpanel rak机房 表格样式 国外免费空间 绍兴高防 135邮箱 速度云 购买国外空间 重庆服务器 黑科云 七牛云存储 双11促销 国外免费网盘 免费赚q币 WHMCS 游戏服务器 在线tracert 一句话木马 饭桶 更多