2017-10-04 2 views
0

사용하여 속성을 구문 분석 : 나는 세 번째 속성 ~ NS2 구문 분석하려고PHP - 없음은 다음 XML을 감안할 때 SimpleXML을

<data xmlns:ns2="..."> 
    <versions> 
      <ns2:version type="HW">E</ns2:version> 
      <ns2:version type="FW">3160</ns2:version> 
      <ns2:version type="SW">3.4.1 (777)</ns2:version> 
    </versions> 
    ... 
</data> 

: 버전 유형 = "SW"를하지만, 다음 코드를 실행할 때 나는 아무것도 얻을 수 없다. .

$s = simplexml_load_file('data.xml'); 

echo $s->versions[2]->{'ns2:version'}; 

이주는 실행 다음과 같은 출력 :

$s = simplexml_load_file('data.xml'); 

var_dump($s->versions); 

enter image description here

해당 속성을 제대로 얻으려면 어떻게해야합니까?

답변

1

.

귀하의 version 요소는 ns2 네임 스페이스에, 그래서 그들에 루프 위해, 당신은 같은 것을 할 필요가 : 만에,

$s = simplexml_load_string($xml); 

foreach ($s->versions[0]->children('ns2', true)->version as $child) { 
    ... 
} 

children() 방법은 현재 태그의 모든 자식을 반환 디폴트의 ​​이름 공간. 다른 네임 스페이스의 요소에 액세스하려면 로컬 별칭과 두 번째 인수 true을 전달하면됩니다.

더 복잡한 부분은 type 속성이 이 아니고이 동일한 네임 스페이스의 일부로 간주된다는 것입니다. 즉, 요소와 속성이 서로 다른 네임 스페이스에 있으므로 표준 $element['attribute'] 양식을 사용하여 액세스 할 수 없습니다. 다행히

, SimpleXML을의 attributes() 방법은 children()과 같은 방식으로 작동 등 글로벌 네임 스페이스의 속성에 액세스하려면, 당신은 그것을 빈 문자열을 전달할 수 있습니다 전체에서

$element->attributes('')->type 

을,이는 다음과 같습니다

$s = simplexml_load_string($xml); 

foreach ($s->versions[0]->children('ns2', true)->version as $child) { 
    echo (string) $child->attributes()->type, PHP_EOL; 
} 

이 버전 당신에게 출력

HW 
FW 
SW 
+0

감사합니다를 얻을 것이다 많이! – BDillan

0

세 번째 특성을 얻으려면.

$s = simplexml_load_file('data.xml'); 
$sxe = new SimpleXMLElement($s); 
foreach ($sxe as $out_ns) { 
    $ns = $out_ns->getNamespaces(true); 
    $child = $out_ns->children($ns['ns2']); 
} 

echo $child[2]; 

아웃 넣어 :

3.4.1 (777)

당신은 적어도 지금까지 SimpleXML을에 관한 한,이 작업을 몇 가지 매우 성가신 XML있어