phpfunctionparsingtextdiscogs-api

How to correctly parse this text with PHP? I'm halfway there


I have this block of text (from the Discogs API) detailing information about bands that contain the word "Pink"...

http://pastebin.com/3vBnC0aE

I'm trying to figure out how to correctly extract the artist names from this block of text. My attempt was:

<?php
    $url = "https://api.discogs.com/database/search?type=artist&q=pink"; // add the resource info to the url. Ex. releases/1

    //initialize the session
    $ch = curl_init();

    //Set the User-Agent Identifier
    curl_setopt($ch, CURLOPT_USERAGENT, 'YourSite/0.1 +http://your-site-here.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);



    function textParser($text, $css_block_name){

        $end_pattern = '], "';

        switch($css_block_name){
            # Add your pattern here to grab any specific block of text
            case 'title';
                $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;
    }

    $blockTitle = textParser($output, 'title');
    echo $blockTitle. '<br/>';



?> 

but that's giving this error:

Warning: stripos(): Offset not contained in string in C:\xampp\htdocs\WellItsFixed3\TTpage1.php on line 41

Line 41 is

$text_portion = substr($text, $start_position, stripos($text, $end_pattern, $start_position) - $start_position + 1);

The ultimate goal is to be able to present the extracted band titles in a list.

Any insight appreciated. Thank you.


Solution

  • This is clearly a JSON encoded string and you are overshooting with your approach. Just do:

    $data = json_decode($your_string);
    

    and $data will contain all the info in a structured way, see the json_decode() manual for more details.