“为foreach()提供的参数无效”阅读XML?

问题描述:

IM gettin: "Invalid argument supplied for foreach()"

in the for each line when trying to read an specific item of the xml

PHP:

$urls="http://www.floatrates.com/daily/usd.xml";       

$url= $urls;
$ch = curl_init();  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
curl_setopt($ch, CURLOPT_URL, $url);  
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);  
curl_close($ch);  
$feed = new SimpleXMLElement($data,LIBXML_NOCDATA); 


foreach ($feed->channel->item as $item) {
$title       = $item->title;
if (preg_match('/ARS/',$title)) {
    echo $title;
}

}

$urls = "http://www.floatrates.com/daily/usd.xml";
$url = $urls;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$feed = new SimpleXMLElement($data, LIBXML_NOCDATA);
foreach ($feed->children() as $item) {
if ("item" == $item->getName()) {
    $title = $item->title;
        if (preg_match('/ARS/', $title)) {
            echo $title;
        }
    }

}

It probably means that $feed does not contain what you expect it to contain, and you are not passing array to foreach Use print_r($feed); to see that it actually contains, and go from there.