2010-05-24 7 views
6

simpleXml 객체가 있고 객체에서 데이터를 읽으려는 경우 PHP를 처음 사용하기 때문에이를 수행하는 방법을 잘 모른다. 객체 세부 정보는 다음과 같습니다.PHP에서 SimpleXML 객체를 반복하는 방법

[설명] 및 [시간]을 읽어야합니다. 고맙습니다.

SimpleXMLElement Object (
    [@attributes] => Array (
     [type] => array 
    ) 
    [time-entry] => Array (
     [0] => SimpleXMLElement Object (
      [date] => 2010-01-26 
      [description] => TCDM1 data management: sort & upload 
      [hours] => 1.0 
      [id] => 21753865 
      [person-id] => 350501 
      [project-id] => 4287373 
      [todo-item-id] => SimpleXMLElement Object (
       [@attributes] => Array (
        [type] => integer 
        [nil] => true 
       ) 
      ) 
     ) 
     [1] => SimpleXMLElement Object (
      [date] => 2010-01-27 
      [description] => PDCH1: HTML 
      [hours] => 0.25 
      [id] => 21782012 
      [person-id] => 1828493 
      [project-id] => 4249185 
      [todo-item-id] => SimpleXMLElement Object (
       [@attributes] => Array (
        [type] => integer 
        [nil] => true 
       ) 
      ) 
) ) ) 

도와주세요. 나는 많은 것을 시도하지만 구문을 올바르게 이해하지 못합니다.

답변

10

그것은 당신이 우리에게 스크린 샷을 주거나 줄 간격 및 들여 쓰기를 줄 수 있다면이 될 것이라고, 위의 내용을 읽고 정말 어렵다 조금 더 나은 당신은 객체에게 SimpleXML이 객체가

$의 XML이있는 경우 , 당신은

$xml->element. 

시간 항목의 요소가 마치 같은 요소에 액세스 할 수있는이 같은 루프를 통해 것 경우 :

foreach($xml->{'time-entry'} as $time_entry) { 
    echo $time_entry->description . "<br />\n"; 
} 
+0

많은 분들께 감사드립니다. 너희들은 바위, 다시 한번 감사드립니다 ... – Aditya

1

질문에서 print_r -ed가있는 객체가 $element 인 경우 다음은 각각 및 hours 값을 출력하면서 두 개의 time-entry 요소를 반복합니다.

foreach ($element->{'time-entry'} as $entry) { 
    $description = (string) $entry->description; 
    $hours  = (string) $entry->hours; 
    printf("Description: %s\nHours: %s\n\n", $description, $hours); 
} 

출력 뭔가 같은 :

Description: TCDM1 data management: sort & upload NFP SubProducers list 
Hours: 1.0 

Description: PDCH1: HTML 
Hours: 0.25 

time-entry 요소 이름 그렇지 않으면 $element->time-entrytime 요소를 읽고 빼기하려고 것이기 때문에 문자열로 1 중괄호에 싸여되어야 함 참고 분명히 우리가 원하는 것이 아닌 entry이라는 상수의 값. 또한 descriptionhours 값은 문자열에 을 캐스팅합니다 (그렇지 않으면 SimpleXMLElement 유형의 개체가됩니다).

1.

variable variables 2. 내가 PHP를 처음 난 그냥 내 개념은 C 프로그래밍에서 온 그렇게 배우기 시작입니다 type casting

+0

많은 사람들에게 고마워, 그것은 잘 작동했습니다. 너희들 바위, 다시 한번 감사드립니다. – Aditya

0

죄송 참조하십시오. 나는 과도한 양의 일/코딩을 여기에서하고 있을지도 모른다. .. 그러나 나는 누군가 사람에 의해 소리 지르게 될 것이고, 배울 것이다라고 확신한다. 이 멋지게 SimpleXMLElement 개체를 처리 할 필요없이 데이터의 모든 개별 비트에 액세스하기위한 배치되는 다시 배열을 반환

:

public $xmlFileInName = 'sample.xml'; 

public $errorMessage = "Failed to open file: "; 

public function actionGetArray() 
{ 
    try { 
     $xml = file_exists($this->xmlFileInName) ? 
     simplexml_load_file($this->xmlFileInName) : 
     exit($this->errorMessage. $this->xmlFileInName); 

     $xmlArray=$this->arrayFromSxe ($xml); 

     echo var_dump($xmlArray); 
    } 
    catch(Exception $e) { 
     echo $e->getMessage(); 
    } 
} 

public function arrayFromSxe($sxe) 
{ 
    $returnArray = array(); 
    foreach ((array)$sxe as $key=>$value) { 
     if(is_array($value) && !$this->is_assoc($value)) { 
      $indies = array(); 
      foreach($value as $secondkey=>$secondvalue) 
       $indies[$secondkey] = $this->arrayFromSxe($secondvalue); 
      $returnArray[$key] = $indies; 
     } 
     else { 
      if(is_object($value)) { 
       $returnArray[$key] = $this->arrayFromSxe($value); 
      } else { 
       $returnArray[$key] = $value; 
      } 
     } 
    } 
    return $returnArray; 
} 

function is_assoc($array) { 
    return (bool)count(array_filter(array_keys($array), 'is_string')); 
} 

주를 당신의 예에서, 즉 여러 XML 태그와 함께 :

[time-entry] => Array (
    [0] => SimpleXMLElement Object (
    ... 
    ) 
    [1] => SimpleXMLElement Object (
    ... 
    ) 

코드에서이 문제를 해결하려면 XML 파일의 구조에 대해 알아야합니다.

$xmlArray=$this->arrayFromSxe ($xml); 

가있을 것이다 어떤 : 이이 줄을 호출 한 후 배열에 반환됩니다

[time-entry][0] 
[time-entry][1] 

그래서 코드가 INT 인덱서를 통해 또는 모든 시간 항목을 반복하기 위해 알아야 할 것 그것들이 xml 요소의 다중 어커런스 인 상황.

내가 말한 것이 의미가 없으면 무시하고 단순히 코드를 관찰하고 평가합니다.

희망이 도움이됩니다.

관련 문제