简体   繁体   English

PHP XML解析器的问题很少

[英]PHP XML parser few questions

I've got XML that looks like: 我有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>

and my PHP parser: 和我的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);
    }
}

This parser works, I does parse the XML and downloadPhoto() function works... here's the code: 这个解析器工作,我解析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);
    }
}

it downloads the picture, but only one picture PER offer so I assume something is wrong with parser code but I really don't know what. 它下载图片,但只有一张图片PER提供,所以我假设解析器代码有问题,但我真的不知道是什么。

I also wanted to change the line in parser: 我还想更改解析器中的行:

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

So $photo_name would be like $offer_signature."_".[[picture number]].".jpg" , for example 20790_01.jpg but the problem is that I don't know how I could code it with foreach. 所以$ photo_name就像$ offer_signature。“_”。[[picture number]]。“。jpg” ,例如20790_01.jpg,但问题是我不知道如何用foreach编写代码。

Question #1 问题#1

You need an additional loop: 你需要一个额外的循环:

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

Question #2 问题2

Just create your own counter: 只需创建自己的计数器:

$count = 0;
foreach($xml->offer as $estate)
{
    foreach($estate->pics as $photos)
    {
        foreach($photos as $pic){
            var_dump(++$count, (string)$pic);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM