从Discogs API获取PHP和输出值



我使用以下代码从discogs的特定记录中获取数据:

//initialize the session
$ch = curl_init();
//Set the User-Agent Identifier
curl_setopt($ch, CURLOPT_USERAGENT, 'MYAPPNAME/0.1 +http://ymysite.com');
//Set the URL of the page or file to download.
curl_setopt($ch, CURLOPT_URL, $url);
//Ask cURL to return the contents in a variable instead of simply echoing them
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the curl session
$output = curl_exec($ch);
//close the session
curl_close ($ch);

我可以回显$output,这将给我一个非常复杂的输出:

{"风格":["蓝调摇滚","摇滚"],"视频":[{"持续时间":200,"嵌入":true,"标题":"滚石乐队-街头斗士","描述":"摇滚乐队-街头霸王","uri":http://www.youtube.com/watch?v=qUO8ScYVeDo"},{"持续时间":2457,"嵌入":true,"标题":"滚石乐队-乞丐宴会全套专辑(单乙烯基混音)","描述":"摇滚乐队-乞丐宴全套专辑","uri":"http://www.youtube.com/watch?v=sRu88xttBrA"}],"series":[],"labels":[{"resource_url":"http://api.discogs.com/labels/5320","entity_type":"1","catno":"SKL 4955","id":5320,"name":"Decca"}]…还有更多…

例如,我如何使用PHP从"styles"中获取信息,从而输出"Blues Rock,Rock&Roll"?也许我也想从"描述"中获得信息,以输出"滚石乐队-乞丐宴会全专辑(单乙烯基混音)"。

亲切问候Johan

<?php
$output = '{"styles": ["Blues Rock", "Rock & Roll"], "videos": [{"duration": 200, "embed": true, "title": "The Rolling Stones - Street Fighting Man", "description": "The Rolling Stones - Street Fighting Man", "uri": "http://www.youtube.com/watch?v=qUO8ScYVeDo"}, {"duration": 2457, "embed": true, "title": "The Rolling Stones - Beggars Banquet FULL ALBUM (mono vinyl mix)", "description": "The Rolling Stones - Beggars Banquet FULL ALBUM (mono vinyl mix)", "uri": "http://www.youtube.com/watch?v=sRu88xttBrA"}], "series": [], "labels": [{"resource_url": "http://api.discogs.com/labels/5320", "entity_type": "1", "catno": "SKL 4955", "id": 5320, "name": "Decca"}]...There is more...';
function textParser($text, $css_block_name){
    $end_pattern = '], "';
    switch($css_block_name){
        # Add your pattern here to grab any specific block of text
        case 'description';
            $end_pattern = '", "';
            break;
    }
    # Name of the block to find
    $needle = ""{$css_block_name}":";
    # Find start position to grab text
    $start_position = stripos($text, $needle) + strlen($needle);
    $text_portion = substr($text, $start_position, stripos($text, $end_pattern, $start_position) - $start_position + 1);
    $text_portion = str_ireplace("[", "", $text_portion);
    $text_portion = str_ireplace("]", "", $text_portion);
    return $text_portion;
}
$blockStyle = textParser($output, 'styles');
echo $blockStyle. '<br/>';
$blockDescription = textParser($output, 'description');
echo $blockDescription. '<br/>';

它将帮助您获取所需的所有区域,您需要根据需要修改脚本。希望它能帮助你:)

相关内容

  • 没有找到相关文章

最新更新