note 45278 modified in ref.simplexml by danbrown

From: Date: Mon, 18 May 2009 01:29:24 +0000
Subject: note 45278 modified in ref.simplexml by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155543@lists.php.net to get a copy of this message
simplexml does not simply handle CDATA sections in a foreach loop. <?php $sx = simplexml_load_string(' <test> <one>hi</one> <two><![CDATA[stuff]]></two> <t> <for>two</for> </t> <multi>one</multi> <multi>two</multi> </test>'); foreach((array) $sx as $tagname => $val) { if (is_string($val)) { // <one> will go here } elseif (is_array($val)) { // <multi> will go here because it happens multiple times } elseif (is_object($val)) { // <t> will go here because it contains tags // <two> will go here because it contains CDATA! } } ?> To test in the loop, do this <?php if (count((array) $val) == 0) { // this is not a tag that contains other tags $val = '' . $val; // now the CDATA is revealed magically. } ?> --was-- simplexml does not simply handle CDATA sections in a foreach loop. <?php $sx = simplexml_load_string(' <test> <one>hi</one> <two><![CDATA[stuff]]></two> <t> <for>two</for> </t> <multi>one</multi> <multi>two</multi> </test>'); foreach((array) $sx as $tagname => $val) { if (is_string($val)) { // <one> will go here } elseif (is_array($val)) { // <multi> will go here because it happens multiple times } elseif (is_object($val)) { // <t> will go here because it contains tags // <two> will go here because it contains CDATA! } } ?> To test in the loop, do this <?php if (count((array) $val) == 0) { // this is not a tag that contains other tags $val = '' . $val; // now the CDATA is revealed magically. } ?> http://php.net/manual/en/ref.simplexml.php

« previous php.notes (#155543) next »