简体   繁体   中英

Limit 1 result in XML query with PHP?

I've got the following PHP code:

$file = 'http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/937a7e45f8f9e50cdb80e21fa50abc39/6479';
if(!$xml = simplexml_load_file($file)) {
    exit('Failed to open '.$file);
}
    foreach($xml->movies->movie->images->image as $image) {
        if(strcmp($image['size'],"cover") == 0) {
                echo "".$image['url']."<br/ >";
        }
    }

In the XML file there are multiple images with size="cover". How can I limit the result of the above code to just 1?

Don't use a foreach statement. $image = $xml->movies->movie->images->image; will give you 1 image (prolly the first one though, that may be a bad thing, depends on your usage).

EDIT, this works pretty good too, and you don't have to rely on the images being in a specific order:

foreach($xml->movies->movie->images->image as $image) {

    if ($image['size'] == 'cover') {
        echo "IMG:".$image['url']."<br/ >";
        break; //STOPS LOOP ON FIRST IMAGE
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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