1

I have been trying to create a foreach loop that will get every ListingId from the XML file but for some reason I can only get one 'Id'

XML STRUCTURE:

<List>
    <Listing>
        <ListingId></ListingId>
</Listing>
    <Listing>
        <ListingId></ListingId>
</Listing>
    <Listing>
        <ListingId></ListingId>
</Listing>
</List>

PHP:

$xml = simplexml_load_file("domain.co.nz/xml.xml");

        foreach($xml->List->Listing->ListingId as $value)
        {

            $xmlArray[] = $value;
        }
4
  • I assume you're using SimpleXML from your incomplete code. It would be worth including those lines as well. Also, despite the name, SimpleXML ends up being less simple than DOM for any non-trivial XML processing. You'll be much better served to learn how to use DOM instead. Commented Nov 14, 2012 at 2:12
  • try list: foreach($xml->List), if $value is tree object, you are on way to parse it, but you'll need to have other nested forcycles. Not sure if is it best way. But good to imagine. Commented Nov 14, 2012 at 2:13
  • @rdlowrey I have included my one and only SimpleXML line of code Commented Nov 14, 2012 at 2:21
  • @JirkaKopřiva List showed all the data but then I still have to go Listing to get the id and I am still getting one Commented Nov 14, 2012 at 2:24

1 Answer 1

1
<?php
$xml = '<List>
    <Listing>
        <ListingId>12</ListingId>
</Listing>
    <Listing>
        <ListingId>13</ListingId>
</Listing>
    <Listing>
        <ListingId>14</ListingId>
</Listing>
</List>';


$xml = simplexml_load_string($xml);
$arr = array();

foreach($xml->Listing as $value)
{
    $arr[] = intval($value->ListingId);
}

print_r($arr); //Array ( [0] => 12 [1] => 13 [2] => 14 )
Sign up to request clarification or add additional context in comments.

4 Comments

David how could I do that from an external document
Exactly like you did. This was just a convenience move for me to be able to test this without creating an xml file. Just stick to $xml = simplexml_load_file("domain.co.nz/xml.xml"); which is doing exactly the same, but from a file.
Thanks David, I have copied and your code and all I am getting is an Array ( )
Changed the foreach to List->Listing->

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.