foreach循环只转储一个变量

时间:2013-05-04 06:14:37

标签: php xml

我有以下代码来查找与preg_match

匹配的xml元素
foreach($xml->Items->Item->AlternateVersions->AlternateVersion->Binding as $BookBinding) { //loop through the xml data to find the correct ASIN for the kindle edition
    foreach ($xml->Items->Item->AlternateVersions->AlternateVersion->ASIN as $Kindlestring)
    {
        var_dump ($BookBinding);
        if (preg_match('/Kindle Edition/i',$BookBinding))
        {
            //do stuff
        }
    }
}

然而,只有var_dumping第一个Binding循环,怎么回事?

1 个答案:

答案 0 :(得分:0)

我只是在这里猜测,因为我不知道XML的结构,但我猜你是在循环错误的XML部分。这是我对你应该做的事情的猜测:

foreach($xml->Items as $item) {
    $bookBinding  = $item->Item->AlternateVersions->AlternateVersion->Binding;
    $kindleString = $item->Item->AlternateVersions->AlternateVersion->ASIN;

    if (preg_match('/Kindle Edition/i',$BookBinding)) {
        //do stuff
    }
}

此外,看起来可能有多个AlternateVersions,因此您可能需要像这样执行嵌套循环:

foreach ($xml->Items as $item) {
    foreach ($item->Item->AlternateVersions as $version) {
        $bookBinding  = $version->AlternateVersion->Binding;
        $kindleString = $version->AlternateVersion->ASIN;

        if (preg_match('/Kindle Edition/i',$BookBinding)) {
            //do stuff
        }
    }
}