Search code examples
phpxmlnsxmlparserxmlreadercdata

XMLReader not reading cdata


I have a problem. I wrote this code but I can't read <![CDATA[Epsilon Yayınları]]>. Items with cdata, when I get them it's empty. Is there an alternative solution?

XML:

<urunler>
  <urun>
    <stok_kod>9789753314930</stok_kod>
    <urun_ad><![CDATA[Kırmızı Erik]]></urun_ad>
    <Barkod>9789753314930</Barkod>
    <marka><![CDATA[Epsilon Yayınları]]></marka>
    <Kdv>8,00</Kdv>
    <satis_fiyat>9,5000</satis_fiyat>
    <kat_yolu><![CDATA[Edebiyat>Hikaye]]></kat_yolu>
    <resim>http://basaridagitim.com/images/product/9789753314930.jpg</resim>
    <Yazar>Tülay Ferah</Yazar>
    <Bakiye>2,00000000</Bakiye>
    <detay><![CDATA[]]></detay>
  </urun>
</urunler>

$xml = new XMLReader;
    $xml->open(DIR_DOWNLOAD . 'xml/'.$xml_info['xml_file_name']);
    $doc = new DOMDocument;

    $product_data = array();

    $i=0;


    while ($xml->read() && $xml->name !== 'urun');
    while ($xml->name === 'urun') {  $i++;

        $node = simplexml_import_dom($doc->importNode($xml->expand(), true));


        var_dump($node->urun_ad); die();

Dump print:

object(SimpleXMLElement)#143 (1) {
  [0]=>
  object(SimpleXMLElement)#145 (0) {
  }
}

Solution

  • It just comes down to how your printing out the value. If you change the var_dump to either of the following, you will get what your after...

    //var_dump($node->urun_ad)
    echo $node->urun_ad.PHP_EOL;
    echo $node->urun_ad->asXML().PHP_EOL;
    

    outputs...

    Kırmızı Erik
    <urun_ad><![CDATA[Kırmızı Erik]]></urun_ad>
    

    One thing to note is that if you want to use the value in another method, you may have to cast it to a string (echo does this automatically). So the first one would be (for example)...

    $urun_ad = (string)$node->urun_ad;