2011-03-25 13 views
5

मैं (इस साइट पर एक पिछले प्रश्न से) निम्नलिखित कोड है जो एक XML फ़ाइल से एक निश्चित छवि को पुन: प्राप्त किया है:बाहरी एक्सएमएल फ़ाइल लोड करें?

<?php 
$string = <<<XML 
<?xml version='1.0'?> 
<movies> 
    <movie> 
    <images> 
     <image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-original.jpg" size="original" width="675" height="1000" id="4bc91de5017a3c57fe00bb7a"/> 
     <image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-mid.jpg" size="mid" width="500" height="741" id="4bc91de5017a3c57fe00bb7a"/> 
     <image type="poster" url="http://cf1.imgobject.com/posters/b7a/4bc91de5017a3c57fe00bb7a/i-am-legend-cover.jpg" size="cover" width="185" height="274" id="4bc91de5017a3c57fe00bb7a"/> 
    </images> 
    </movie> 
</movies> 
XML; 

$xml = simplexml_load_string($string); 

foreach($xml->movie->images->image as $image) { 

    if(strcmp($image['size'],"cover") == 0) 
     echo $image['url']; 
} 

?> 

मैं जानना चाहते हैं क्या है, मैं कैसे बाहरी एक्सएमएल फ़ाइल लोड कर सकते हैं वास्तविक PHP में XML डेटा लिखने के बजाय ऊपर दिखाया गया है?

उत्तर

12

Procedurally, simple_xml_load_file उपयोग कर सकते हैं।

$file = '/path/to/test.xml'; 
if (file_exists($file)) { 
    $xml = simplexml_load_file($file); 
    print_r($xml); 
} else { 
    exit('Failed to open '.$file); 
} 

आप ओओ इंटरफेस, SimpleXMLElement का उपयोग करने पर भी विचार करना चाहेंगे।

संपादित करें: यदि फ़ाइल कुछ दूरस्थ यूआरआई पर है, file_exists काम नहीं करेगा।

$file = 'http://example.com/text.xml'; 
if(!$xml = simplexml_load_file($file)) 
    exit('Failed to open '.$file); 
print_r($xml); 
+0

'file_exists' स्थानीय सिस्टम पर उस फ़ाइल की जांच कर रहा है, जो फ़ाइल के दूरस्थ सर्वर पर मौजूद नहीं है, जो ऐसा नहीं कर सकता है। – cantlin

+0

धन्यवाद डे! :) मेरा मानना ​​है कि यह अब काम कर रहा है –

2

$xml = simplexml_load_file('path/to/file');

संबंधित मुद्दे