Search code examples
phpxmlreader

xmlreader child node value


hello i have this xml:

<pola_wlasne>
  <pole>
    <nazwa><![CDATA[STAN 1]]></nazwa>
    <wartosc><![CDATA[5.33]]></wartosc>
  </pole>
  <pole>
    <nazwa><![CDATA[Gatunek]]></nazwa>
    <wartosc><![CDATA[I]]></wartosc>
  </pole>
  <pole>
    <nazwa><![CDATA[pal]]></nazwa>
    <wartosc><![CDATA[65,0900]]></wartosc>
  </pole>
  <pole>
    <nazwa><![CDATA[op.]]></nazwa>
    <wartosc><![CDATA[1,4150]]></wartosc> // <- how to read only this value?
  </pole>
</pola_wlasne>

and I want to read only one node with xmlreader. I tried to read parent's value and then go to next node but it dosen't work.

if ($reader->value == 'op.'){
              $reader->next('wartosc');
            }
(..)
case 'wartosc':
$reader->value; // <-- read all elements
break;

but it was read all values from node name wartosc. I can't add some attributes to this xml.


Solution

  • It's a little complicated with XMLReader, you have to iterate through all XML and set proper flags when next node should be readed. Also, you have CDATA sections, so you need to check it for proper value readings.

    Code:

    $wartosc = 0; // flags
    $nazwa = 0;
    while ($xml->read()) {
       if($wartosc && $xml->nodeType == XMLReader::CDATA){ 
       // if we are in proper 'wartosc' node, and it's CDATA section
            echo $xml->value;   // read value
            break;  // end reading
       }
    
       if($xml->name == 'nazwa'){ // if we are in node 'nazwa'
            $nazwa = 1; // set flag for reading next CDATA
       }
    
       if($nazwa && $xml->nodeType == XMLReader::CDATA){ 
       // if we are in 'nazwa' node, and it's CDATA section
            if($xml->value == 'op.'){   // .. and it's have 'op.' value
                $wartosc = 1; // set flag for reading next 'wartosc' node value
            } else {
                $xml->next('pole'); // otherwise, skip to next 'pole' node
            }
       }
    } 
    

    So it return's proper: 1,4150 value

    Mayby there is a simpler way to do this, I'm not exactly familiar with XMLReader, used SimpleXML for most cases.