我需要从Zazzle的API中提取XML RSS提要的每个项目中的三件事。
以下是Feed:https://feed.zazzle.com/cityofhoops/rss
我需要从每个项目中获取标题,价格,缩略图和guid(链接)并将其添加到数组中。我计划将此数组编码为JSON,以便我可以使用AJAX获取它并构建商店视图。
我该怎么做?我尝试过使用foreach并阅读文档,但我没有理解如何获取每个项目的值,无论我尝试什么,它似乎都不起作用。
这是我到目前为止的代码:
$xml = simplexml_load_file('http://feed.zazzle.com/cityofhoops/rss');
echo '<pre>';
//echo json_encode($xml);
foreach($xml as $child){
$new[] = [
'img'=>(string)$child->attributes()->url,// ???
'link'=>,
'price'=>,
];
}
print_r($xml, false);
答案 0 :(得分:1)
您需要使用->children()
方法并提供命名空间以获取所需的值。例如:
$data = array();
// add LIBXML_NOCDATA if you need those inside the character data
$xml = simplexml_load_file('http://feed.zazzle.com/cityofhoops/rss', 'SimpleXMLElement', LIBXML_NOCDATA);
foreach($xml->channel->item as $item) {
$media = $item->children('media', 'http://search.yahoo.com/mrss/');
$data[] = array(
'title' => (string) $item->title,
'price' => (string) $item->price,
'guid' => (string) $item->guid,
'link' => (string) $item->link,
'author' => (string) $item->author,
// 5.4 above dereference
'thumbnail' => (string) $media->thumbnail->attributes()['url'],
// if below, just assign $media->thumbnail->attributes() inside another variable first
// then access it there
);
}
echo '<pre>';
print_r($data);
应输出如下内容:
Array
(
[0] => Array
(
[title] => City Of Hoops: Grind Mode Mugs
[price] => $24.95
[guid] => http://www.zazzle.com/city_of_hoops_grind_mode_mugs-168144869293766796
[link] => http://www.zazzle.com/city_of_hoops_grind_mode_mugs-168144869293766796
[author] => CityOfHoops
[thumbnail] => http://rlv.zcache.com/city_of_hoops_grind_mode_mugs-rb83d2f2a678e4c5fa5287de6cc845a3a_x7jgp_8byvr_152.jpg
)