So I'm trying to iterate through an XML feed and paginate it but I've run into a problem. When I try to get the index (key) of the current array it outputs a string "campDetails" on every iteration instead of an incrementing integer like 0,1,2,3
Here is a sample of the XML format
<campaigns> <campDetails> <campaign_id>2001</campaign_id> <campaign_name>Video Chat Software</campaign_name> <url>http://www.fakeurl.com</url> </campDetails>
<?php
$call_url = "https://www.fakeurl.com";
if($xml = simplexml_load_file($call_url, "SimpleXMLElement", LIBXML_NOCDATA)):
foreach($xml as $i => $offers):
$offer_link = $offers->url;
$offer_raw_name = $offers->campaign_name;
echo $i . " " . $offer_link; ?> </br> <?php echo $offer_raw_name;
endforeach;
endif;
?>
Output to be expected:
0 http://www.fakeurl.com
Video Chat Software
Actual output:
campDetails http://www.fakeurl.com
Video Chat Software
EDIT: Thank you for your answers everyone. It seems I was given incorrect information from another question on here. I was told that $i would keep a numerical index for the current iteration.
print_r($xml); (obviously more results but this is the first)
SimpleXMLElement Object ( [campDetails] => Array ( [0] => SimpleXMLElement Object ( [campaign_id] => 2001 [campaign_name] => Video Chat Software [url] => http://www.fakeurl.com/ )
Instead of using the current foreach and associative array, I pushed all values to an indexed array.
In this usage of foreach
, $i
is not a numeric index but a key. In this case, the key for the current object is campDetails
.
Alternative Code
$i = 0;
foreach($xml as $offer) {
// your code...
++$i;
}
For more details on the type of object you receive from simplexml_load
read the docs or debug with print_r($xml);
.
Your $i
is not an index. You could do something like:
$index = 0;
foreach($xml as $i => $offers):
$offer_link = $offers->url;
$offer_raw_name = $offers->campaign_name;
echo $index++ . " " . $offer_link; ?> </br> <?php echo $offer_raw_name;
endforeach;
simplexml_load_file
returns an object, a foreach
loop will iterate over its fields, and $i
will hold the current field's key.
If you want a numeric counter as well, just increment on your own:
$j = 0;
foreach($xml as $i => $offer){
// do your stuff
$j++;
}
Its a bit redundant, but you can use something like:
$x = 0;
foreach($xml as $i => $offers):
// other stuff
echo $x . " " . $offer_link; ?> </br> <?php echo $offer_raw_name;
$x++;
endforeach;
You can also streamline your echo line like so:
echo "$i $offer_link <br> $offer_raw_name";