<?php
/*
 xml로 자료 가져오기
 ut8-8로 한글 코딩을 해야함.
*/
class XmlSimple
{
    public $xml_obj;
    private $num_rows = 0;  # query 엘리멘트 갯수
 
    #@ void
    # xpath = xml 파일 경로
    public function __construct($url){
        //if(!self::isExists($xpath))
                //throw new ErrorException('파일이 없어 어데간겨 잘 찾아봐',__LINE__);
 
        # 데이타 가져오기
        //if(!$xml_data = file_get_contents($xpath))
                //throw new ErrorException('No data',__LINE__);

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  ob_start();

  curl_exec($ch);
  curl_close($ch);
  $xml_data = ob_get_contents();

  ob_end_clean();

  //return $string;


  $xml_data = preg_replace('/\&/', '&amp;', $xml_data);


        # simple xml
        $this->xml_obj = new SimpleXMLElement($xml_data);
  //$this->xml_obj = new XMLParser($xml_data);
    }
 
    #@ return xml array
    # navigation/item
    public function query($query){
        $result=$this->xml_obj->xpath($query);
        $this->num_rows =count($result);
    return $result;
    }
 
    #@return array
    public function fetch($result)
    {
        $loop =array();
        for($i=0; $i<$this->num_rows; $i++)
        {
            // attributes만 있을 수 있음
            $attr_count=count($result[$i]->attributes());
            if($attr_count>0)    {
                $loop2=&$loop[$i]['attr'];
                foreach($result[$i]->attributes() as $k2=>$kv){
                    $loop2[$k2]=strval($kv);
                }
            }
 
            // child
            if(count($result[$i])){
                foreach($result[$i] as $k=>$v)
                {             
                    // child -> attributes
                    $attr_count=count($v->attributes());
                    if($attr_count>0)    {
                        $loop3=&$loop[$i][$k][]['attr'];
                        foreach($v->attributes() as $k3=>$k3v){
                            $loop3[$k3]=strval($k3v);
                        }
                    }else{
                        $loop[$i][$k]=strval($v);
                    }
                }
            }
        }
    return $loop;
    }
 
    #@ return
    public function __get($propertyName){
        if(property_exists(__CLASS__,$propertyName)){
            return $this->{$propertyName};
        }
    }
 
    # 로컬 파일인지 체크
    protected function isExists($filename){
        if(!file_exists($filename)) return false;
    return true;
    }
}

 

$sx =new XmlSimple('xml가져올 url주소');
$result=$sx->query('root');     //최상위 root
$row=$sx->fetch($result);

$result=$sx->query('xmldata'); //반복 엘리먼트
$row=$sx->fetch($result);