loadfile_get_contents

file_get_contents  时间:2021-05-19  阅读:()
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/)

无视CC攻击CDN ,DDOS打不死高防CDN,免备案CDN,月付58元起

快快CDN主营业务为海外服务器无须备案,高防CDN,防劫持CDN,香港服务器,美国服务器,加速CDN,是一家综合性的主机服务商。美国高防服务器,1800DDOS防御,单机1800G DDOS防御,大陆直链 cn2线路,线路友好。快快CDN全球安全防护平台是一款集 DDOS 清洗、CC 指纹识别、WAF 防护为一体的外加全球加速的超强安全加速网络,为您的各类型业务保驾护航加速前进!价格都非常给力,需...

Spinservers:美国圣何塞机房少量补货/双E5/64GB DDR4/2TB SSD/10Gbps端口月流量10TB/$111/月

Chia矿机,Spinservers怎么样?Spinservers好不好,Spinservers大硬盘服务器。Spinservers刚刚在美国圣何塞机房补货120台独立服务器,CPU都是双E5系列,64-512GB DDR4内存,超大SSD或NVMe存储,数量有限,机器都是预部署好的,下单即可上架,无需人工干预,有需要的朋友抓紧下单哦。Spinservers是Majestic Hosting So...

NameCheap新注册.COM域名$5.98

随着自媒体和短视频的发展,确实对于传统的PC独立网站影响比较大的。我们可以看到云服务器商家的各种促销折扣活动,我们也看到传统域名商的轮番新注册和转入的促销,到现在这个状态已经不能说这些商家的为用户考虑,而是在不断的抢夺同行的客户。我们看到Namecheap商家新注册域名和转入活动一个接一个。如果我们有需要新注册.COM域名的,只需要5.98美元。优惠码:NEWCOM598。同时有赠送2个月免费域名...

file_get_contents为你推荐
工艺美术品设计专业补丁安装前必读支持ipadcyclesios8支持ipad支持ipad城乡居民社会养老保险人脸识别生存认证重庆网通重庆联通现在有哪些资费???eacceleratorCentOS5.2下安装eAccelerator,怎么都装不上勒索病毒win7补丁我的电脑是windows7系统,为什么打不了针对勒索病毒的补丁(杀毒软件显
电信服务器租赁 香港ufo 英文简历模板word 美国php主机 iis安装教程 lighttpd tk域名 国外php空间 国内php空间 泉州移动 爱奇艺vip免费试用7天 最好的qq空间 免费网页空间 google台湾 韩国代理ip 新加坡空间 酸酸乳 云销售系统 服务器托管价格 phpinfo 更多