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

Virmach:1核/512M1核M1核512M/夏季美国vps促销,年付$7.2,9月更换AMD平台

virmach怎么样?virmach家这几年非常火,从商家的黑五闪购开始,以超低的价格吸引了大批的国人客户,而且商家的机器还是非常稳定的,站长手里的4.75刀年付已经用了两年了,非常稳定,不过商家到国内的线路一般,目前商家新上了夏季优惠促销,价格低到发指,年付7.2美元起,商家反馈将在9月开始更换AMD+NVMe平台,这个消息从年初就有了,不过一直没有更换,目前这个时间也不确定是否准确。点击进入:...

酷锐云香港(19元/月) ,美国1核2G 19元/月,日本独立物理机,

酷锐云是一家2019年开业的国人主机商家,商家为企业运营,主要销售主VPS服务器,提供挂机宝和云服务器,机房有美国CERA、中国香港安畅和电信,CERA为CN2 GIA线路,提供单机10G+天机盾防御,提供美国原生IP,支持媒体流解锁,商家的套餐价格非常美丽,CERA机房月付20元起,香港安畅机房10M带宽月付25元,有需要的朋友可以入手试试。酷锐云自开业以来一直有着良好的产品稳定性及服务态度,支...

IntoVPS:按小时计费KVM月费5美元起($0.0075/小时),6个机房可选

IntoVPS是成立于2004年的Hosterion SRL旗下于2009年推出的无管理型VPS主机品牌,商家提供基于OpenStack构建的VPS产品,支持小时计费是他的一大特色,VPS可选数据中心包括美国弗里蒙特、达拉斯、英国伦敦、荷兰和罗马尼亚等6个地区机房。商家VPS主机基于KVM架构,最低每小时0.0075美元起($5/月)。下面列出几款VPS主机配置信息。CPU:1core内存:2GB...

file_get_contents为你推荐
考生itunesIntentsandroid绑定ipad模式ios8支持ipad支持ipad支付applexp如何关闭445端口Windows XP 怎么关闭445端口,我是电脑小白,求各位讲详细点重庆宽带测速重庆云阳电信宽带测速网址谁知道,帮个忙?windows键是哪个Windows键是哪个键啊?
台湾虚拟主机 shopex虚拟主机 北京服务器租用 工信部域名备案系统 贝锐花生壳域名 独享100m 42u标准机柜尺寸 租空间 admit的用法 亚马逊香港官网 酷番云 东莞idc shuang12 美国盐湖城 东莞服务器托管 工信部网站备案查询 免备案jsp空间 碳云 godaddyssl phpinfo 更多