【问题标题】:How to extract media:* namespace values in XML?如何在 XML 中提取 media:* 命名空间值?
【发布时间】:2014-09-27 14:45:27
【问题描述】:

我需要从 Zazzle 的 API 的 XML RSS 提要的每个项目中提取三项内容。

这里是提要: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);

【问题讨论】:

    标签: php xml json rss simplexml


    【解决方案1】:

    您需要使用-&gt;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
            )
    

    【讨论】:

    • 所以基本上,“媒体;*”在标签中没有任何意义?我可以给标签名称吗?如果是这样,谢谢,我现在了解我需要了解的有关 xml 的基础知识。
    • @r3wt 当然你必须提供节点的名称,否则会导致错误
    猜你喜欢
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 2013-05-15
    • 2016-05-30
    • 1970-01-01
    相关资源
    最近更新 更多