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/)

RackNerd:特价美国服务器促销,高配低价,美国多机房可选择,双E526**+AMD3700+NVMe

racknerd怎么样?racknerd今天发布了几款美国特价独立服务器的促销,本次商家主推高配置的服务器,各个配置给的都比较高,有Intel和AMD两种,硬盘也有NVMe和SSD等多咱组合可以选择,机房目前有夏洛特、洛杉矶、犹他州可以选择,性价比很高,有需要独服的朋友可以看看。点击进入:racknerd官方网站RackNerd暑假独服促销:CPU:双E5-2680v3 (24核心,48线程)内存...

HostWebis:美国/法国便宜服务器,100Mbps不限流量,高配置大硬盘,$44/月起

hostwebis怎么样?hostwebis昨天在webhosting发布了几款美国高配置大硬盘机器,但报价需要联系客服。看了下该商家的其它产品,发现几款美国服务器、法国服务器还比较实惠,100Mbps不限流量,高配置大硬盘,$44/月起,有兴趣的可以关注一下。HostWebis是一家国外主机品牌,官网宣称1998年就成立了,根据目标市场的不同,以不同品牌名称提供网络托管服务。2003年,通过与W...

Linode十八周年及未来展望

这两天Linode发布了十八周年的博文和邮件,回顾了过去取得的成绩和对未来的展望。作为一家运营18年的VPS主机商,Linode无疑是有一些可取之处的,商家提供基于KVM架构的VPS主机,支持随时删除(按小时计费),可选包括美国、英国、新加坡、日本、印度、加拿大、德国等全球十多个数据中心,所有机器提供高出入网带宽,最低仅$5/月($0.0075/小时)。This month marks Linod...

file_get_contents为你推荐
上海fastreport2支持ipadexportingjava支持ipadcss3圆角怎样用css实现圆角矩形?tracerouteTRACEROUTE的作用是什么win7telnet怎样在win7下打开telnet 命令google分析google analysis干什么用的?google分析怎样学会使用谷歌分析? 我自己想往网站分析走。重庆电信测速重庆电信对BT开始限制了?
手机网站空间 东莞服务器租用 免费linux主机 百度云100as 美国主机论坛 wordpress技巧 云全民 web服务器的架设 工作站服务器 网站卫士 vip域名 流媒体加速 中国电信网络测速 帽子云排名 免费网络 umax 德国代理 超低价 免费论坛空间 更多