Re: XML Parsing simpleXML Arrays Question
| From: | Jim Lucas | Date: | Mon, 15 Jan 2007 06:43:53 +0000 |
| Subject: | Re: XML Parsing simpleXML Arrays Question | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-247097@lists.php.net to get a copy of this message | ||
Richard Luckhurst wrote:
Hi List I have taken the advice of a number of people on the list and am back trying to write my XML parser using SimpleXML. I am having a problem and I believe the problem is my lack of understanding of arrays and simpleXML in spite of much google searching and manual reading. I would appreciate some help. The piece of XML I am parsing is as follows. I am working with a small section to see if I can get my head around it. <?xml version="1.0" encoding="UTF-8"?> <?ypsilon RNGSchema="fareResponse.rnc" type="compact"?> <fareResponse cntTarifs="122" offset="0"> <vcrSummary><vcr minPrice="1667" maxPrice="1667" totalTarifs="1" currency="USD">AA</vcr> <vcr minPrice="1374" maxPrice="4704" totalTarifs="2" currency="USD">PR</vcr></vcrSummary> </fareResponse> If I use the following $file = "test.xml";$data = simplexml_load_file($file); Just to confirm your data structure, do a var_dump($data) right here and see what the output is
foreach ($data->vcrSummary as $vcrSummary){ var_dump($vcrSummary); }Then I get object(SimpleXMLElement)#5 (1) { ["vcr"]=> array(2) {[0]=> string(2) "AA" [1]=> string(2) "PR"} } Which is pretty much what I would expect as there are 2 vcr tags. If I then use $file = "test.xml";$data = simplexml_load_file($file);right here you, at least from the example above, you need to be using $data->vcrSummary as the first parameter of the foreach loop
foreach($data as $vcrSummary)
{
then here I would be using another foreach loop, because the $vcrSummary->vcr is an array with two indexes 0 and 1... So
foreach ( $vcrSummary->vcr AS $v ) {
echo "{$v}\n";
}
$z = $vcrSummary->vcr;
print "$z \n";
}
I get 3 blank lines and then AA which is the first of the two vcr values. The
examples I am looking at suggest I should have gotten both of the vcr values.
Many of the examples I am looking at say to use echo instead of print, eg
echo $vcrSummary->vcr;
if done correctly, this should echo "Array" and maybe a warning. :(
Jim Lucas
and that just gives me AA and not both values that I would expect. Can anyone point me in the right direction here. Regards,Richard Luckhurst Product DevelopmentExodus Systems - Sydney, Australia. rluckhurst@resmaster.com