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/)
易探云怎么样?易探云是目前国内少数优质的香港云服务器服务商家,目前推出多个香港机房的香港云服务器,有新界、九龙、沙田、葵湾等机房,还提供CN2、BGP及CN2三网直连香港云服务器。近年来,许多企业外贸出海会选择香港云服务器来部署自己的外贸网站,使得越来越多的用户会选择易探云作为网站服务提供平台。今天,云服务器网(yuntue.com)小编来谈谈易探云和易探云服务器怎么样?具体香港云服务器多少钱1个...
六一云 成立于2018年,归属于西安六一网络科技有限公司,是一家国内正规持有IDC ISP CDN IRCS电信经营许可证书的老牌商家。大陆持证公司受大陆各部门监管不好用支持退款退现,再也不怕被割韭菜了!主要业务有:国内高防云,美国高防云,美国cera大带宽,香港CTG,香港沙田CN2,海外站群服务,物理机,宿母鸡等,另外也诚招代理欢迎咨询。官网www.61cloud.net最新直销劲爆...
昔日数据怎么样?昔日数据新上了湖北十堰云服务器,湖北十堰市IDC数据中心 母鸡采用e5 2651v2 SSD MLC企业硬盘 rdid5阵列为数据护航 100G高防 超出防御峰值空路由2小时 不限制流量。目前,国内湖北十堰云服务器,首月6折火热销售限量30台价格低至22元/月。(注意:之前有个xrhost.cn也叫昔日数据,已经打不开了,一看网站LOGO和名称为同一家,有一定风险,所以尽量不要选择...
file_get_contents为你推荐
标准论文格式范例规范formgraphpqqgraph支持ipad支持ipad平台操作使用手册win7telnetWin7系统中的telnet命令如何应用?win7telnetwindows7的TELNET服务在哪里开启啊x-router思科路由器有线端无法上网,而无线段却可以,用的是PPPOE拨号上网,一开始两种方法都不可以,检查宽win7如何关闭445端口如何关闭WIN7自动配置 IPV4 地址 169.254
荷兰vps 187邮箱 vpsio pccw 私服服务器 网站保姆 最好看的qq空间 idc是什么 秒杀汇 腾讯实名认证中心 电信托管 google台湾 美国盐湖城 黑科云 免费赚q币 脚本大全 湖南铁通 连连支付 赵 免费网络电视直播 更多