2011-03-25 5 views
5

나는 XML 파일에서 특정 이미지를 검색 (이 사이트에 앞의 질문에서) 다음 코드를했다 : 나는 외부 XML 파일을 내가 알고 싶습니다 무엇외부 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

, 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); 
} 

또한 OO 인터페이스 SimpleXMLElement을 사용해보십시오.

편집 : 파일이 원격 URI에있는 경우 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');