0

我的 XML 看起来像:

<?xml version="1.0" encoding="Windows-1250" ?> 
<offers>
<offer>
<offer_num>20790</offer_num>
<pics>
    <pic>http://old.mls.org.pl/pic!get.action?obrazId=11651</pic>
    <pic>http://old.mls.org.pl/pic!get.action?obrazId=16906</pic>
    <pic>http://old.mls.org.pl/pic!get.action?obrazId=9641</pic>
    <pic>http://old.mls.org.pl/pic!get.action?obrazId=9742</pic>
</pics>
</offer>
<offer>
<offer_num>20791</offer_num>
<pics>
    <pic>http://old.mls.org.pl/pic!get.action?obrazId=1432t</pic>
    <pic>http://old.mls.org.pl/pic!get.action?obrazId=12346906</pic>
</pics>
</offer>
</offers>

和我的 PHP 解析器:

foreach($xml->offer as $estate)
{
    $offer_signature = rtrim($estate->offer_num);
    $offer_photos = array();
    foreach($estate->pics as $photos)
    {
        $photo_url = $photos->pic;
        $photo_name = $offer_signature."_".md5($photo_url).".jpg";
        $offer_photos[] = $photo_name;
        downloadPhoto($photo_url, $photo_name);
    }
}

这个解析器工作,我解析 XML 和 downloadPhoto() 函数工作......这是代码:

function downloadPhoto($photo_url, $photo_name)
{
    $dt = @file_get_contents($photo_url);
    if($dt)
    {
        $h = fopen(photo_path.$photo_name, 'w+');
        flock($h, 2);
        fwrite($h, $dt, strlen($dt));
        flock($h, 3);
        fclose($h);
    }
}

它下载图片,但每次只提供一张图片,所以我认为解析器代码有问题,但我真的不知道是什么。

我还想更改解析器中的行:

$photo_name = $offer_signature."_".md5($photo_url).".jpg";

所以 $photo_name 就像$offer_signature."_".[[picture number]].".jpg",例如20790_01.jpg但问题是我不知道如何使用 foreach 对其进行编码。

4

1 回答 1

2

问题 #1

你需要一个额外的循环:

foreach($xml->offer as $estate)
{
    $offer_signature = rtrim($estate->offer_num);
    $offer_photos = array();
    foreach($estate->pics as $photos)
    {

        foreach($photos as $pic){
            $photo_url = $pic;
            $photo_name = $offer_signature."_".md5($photo_url).".jpg";
            //$offer_photos[] = $photo_name;
            var_dump((string)$photo_url, (string)$photo_name);
        }
    }
}

问题2

只需创建自己的计数器:

$count = 0;
foreach($xml->offer as $estate)
{
    foreach($estate->pics as $photos)
    {
        foreach($photos as $pic){
            var_dump(++$count, (string)$pic);
        }
    }
}
于 2012-11-15T12:24:19.280 回答