Computer >> 컴퓨터 >  >> 프로그램 작성 >> PHP

PHP에서 DOM 요소를 어떻게 반복합니까?

<시간/>

다음은 XML 데이터(입력) −

<other data>
   <foo> <bar></bar>
      <value/>
   <pub></pub> </foo>
<foo>
   <bar></bar> <pub></pub>
</foo>
<foo>
   <bar></bar> <pub></pub>
</foo>
</other data>

DOM 개체의 요소를 반복합니다.

예시

$elements = $dom->getElementsByTagName('foo');
$data = array();
foreach($elements as $node){
   foreach($node->childNodes as $child) {
      $data[] = array($child->nodeName => $child->nodeValue);
   }
}

출력

이것은 다음과 같은 출력을 생성합니다 -

Every ‘foo’ tag will be iterated over and specific ‘bar’ and ‘pub’ value will be obtained, 
i.e specific child nodes can be accessed by their names itself.

XML 파일의 요소는 XML 파일의 모든 노드에 대해 foreach 루프를 실행하여 얻습니다. foreach 루프 내에서 메인 노드의 자식 노드를 참조하고 자식 노드의 자식 값에 접근할 수 있습니다.