2011-03-30 5 views
3

XML의 첫 번째 태그 속성을 읽으려고합니다. 가 여기에 XML 구조SimpleXML - 첫 번째 태그의 속성을 가져올 수 없습니다.

<myxml timestamp="1301467801"> 
    <tag1>value1</tag1> 
    <tag2>value2</tag2> 
    … 
</myxml> 

입니다 그리고 여기가 타임 스탬프 속성을 얻으려고 방법

$timestamp = $xml->myxml->attributes()->timestamp; //gives Node no longer exists warning 
if($xml->myxml && $xml->myxml->attributes()){ //Doesn't enter this loop 
    $arr = $xml->myxml->attributes(); 
    $timestamp = $arr['timestamp']; 
} 

누군가가 알려 주시기 바랍니다 수 (여기에 모두 나열이 접근을 시도, 아무도는 작동하지 않습니다) 속성의 값을 어떻게 얻을 수 있습니까? 감사.

+0

재현 할 테스트 케이스를 제공하시기 바랍니다. 위의 예에서 당신이 뭘 잘못하고 있는지 추측하기는 어렵습니다. 나의 가정은'$ xml'은 실제로'-> myxml' 대신에''노드를 가리킨다는 것입니다. 그러나 노드는 더 이상 존재하지 않습니다 경고는 다른 오용을 암시 할 수 있습니다. – Gordon

답변

9

$xml이 루트 요소를 실제로 가리키기 때문입니다. 올바른 사용법은 다음과 같습니다

$timestamp = $xml->attributes()->timestamp;

2

[만큼 그들은 노드의 네임 스페이스에 속으로] 속성에 액세스 할 수있는 권한 방법은 배열 표기법을 사용하는 것입니다. 네임 스페이스 속성에 대해서는 attributes을 예약하십시오.

또한 루트 노드 다음에 XML 문서를 나타내는 변수의 이름을 지정해야합니다. 많은 혼란을 막는 좋은 방법입니다.

$myxml = simplexml_load_string(
    '<myxml timestamp="1301467801"> 
     <tag1>value1</tag1> 
     <tag2>value2</tag2> 
    </myxml>' 
); 

echo $myxml['timestamp']; 
1
<?php 
$myxml = simplexml_load_string(
     '<myxml timestamp="1301467801"> 
     <tag1>value1</tag1> 
     <tag2>value2</tag2> 
    </myxml>' 
); 

$test = $myxml['timestamp']; 
// will asign simpleXMLElement 
echo $test; // -> will print nothing 

// you need to cast the simpleXMLElement attribute as STRING!!! 
$test = (string)$myxml['timestamp']; 
echo $test; 
?> 
관련 문제