2010-04-22 3 views
2

다음은 XML 샘플 코드입니다.PHP XMLReader를 통해 XML 속성을 구문 분석

<m:ad xmlns:m="http://www.w3c.org/soap"> 
    <title><![CDATA[TITLE]]></title> 
    <phone>123456789</phone> 
    <attributeGroup> 
     <attribute id="14" name="A1">40</attribute> 
     <attribute id="15" name="A2">50</attribute> 
    </attributeGroup> 
</m:ad> 

나는 단지 PHP의 XMLReader 값

$reader = new XMLReader();   
if ($reader->name == "title" && $reader->nodeType ==XMLReader::ELEMENT) { 
    echo $reader2->read(); // will get TITLE 
} 

하지만 어떻게 A1, A2 속성 수에 도착하는 것을 알고있다. 저는 40 세와 50 세를 모두 갖고 싶습니다.

답변

5
$reader = new XMLReader(); 
$reader->xml('<m:ad xmlns:m="http://www.w3c.org/soap"> 
    <title><![CDATA[TITLE]]></title> 
    <phone>123456789</phone> 
    <attributeGroup> 
     <attribute id="14" name="A1">40</attribute> 
     <attribute id="15" name="A2">50</attribute> 
    </attributeGroup> 
</m:ad>'); 


while ($reader->read()) { 
    if ( $reader->nodeType ==XMLReader::ELEMENT && $reader->name == "attribute") { 
    printf("id=%s, name=%s\n", $reader->getAttribute('id'), $reader->getAttribute('name')); 
    } 
} 

인쇄

id=14, name=A1 
id=15, name=A2 
+0

+1,하지만 난이 공급됩니다 속성 무엇 무엇을 모른다면? – SDC

+0

SDC : 그 질문은 내가 대답하기에는 너무 광범위하다. 무엇을 성취하려고합니까? 그 스키마가 당신이 찾고있는 것일 수도 있고 odata와 같은 것일 수도 있습니다. 아마도 XSL (t)로 변환하는 것이 대답 일 수도 있고 완전히 다른 것일 수도 있습니다 : – VolkerK

+5

'$ reader- > attributeCount' 그리고 나서'for()'루프를 사용하여'$ reader-> moveToAttributeNo()'를 사용하여 각 속성을 차례로 읽는다. 그렇게하면 내가 무엇을 할 것인지 미리 알 필요없이 모든 속성에 액세스 할 수 있습니다. – SDC