从多个xml元素创建foreach数组

时间:2012-11-14 01:58:40

标签: php xml arrays

我一直在尝试创建一个foreach循环,它将从XML文件中获取每个ListingId但由于某种原因我只能获得一个'Id'

XML结构:

<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;
        }

1 个答案:

答案 0 :(得分: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 )