2

the followings are XML sample code.

<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>

I only know PHP XMLReader to get value

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

But how to get attribute A1, A2 . I would like to get 40, and 50 both .

1 Answer 1

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'));
  }
}

prints

id=14, name=A1
id=15, name=A2
Sign up to request clarification or add additional context in comments.

3 Comments

+1, but what if I don't know what attributes will be supplied?
SDC: That question is a little bit too broad for me to answer. What are you trying to achieve? Could be that schemas are what you're looking for, or something like odata, may even be that transforming via XSL(t) is the answer ....or something completely different ;-)
I ended up using $reader->attributeCount and then a using for() loop to read each attribute in turn using $reader->moveToAttributeNo(). That allows me to access all attributes, without having to know in advance what they will be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.