phpdomsoundcloud

How to retrieve a soundcloud ID from the DOM


I want to embed a SoundCloud file by its URL: http://soundcloud.com/oembed?url=http://soundcloud.com/kiwinest/linkin-park-iridescent This URL gives every detail of the sound file including HTML embed codes.

I want to remove all codes and want just the sound id, which is is 17181143 I'm using this code:

<?php
include('lib/simple_html_dom.php');

$html = file_get_html('http://soundcloud.com/oembed?url=http://soundcloud.com/kiwinest/linkin-park-iridescent');

if ($html) {
    foreach ($html->find('object') as $obj) {
        foreach ($obj->find('param') as $par) {
            if ($par->name == 'movie') {
                $embed = parse_url($par->value);
                parse_str(urldecode($embed['query']), $val);
                if (array_key_exists('url', $val)) {
                    $url = parse_url($val['url']);
                    $path = explode('/', $url['path']);
                    $code = array_pop($path);
                    if (is_numeric($code)) {
                        echo 'CODE: ' . $code . PHP_EOL;
                    }
                }
            }
        }
    }
}

But this gives no output.


Solution

  • Make sure $html is NOT empty; as in make sure you're actually getting something back from that URL and it's stored in that variable. My answer was shorter than his crazy big O nightmare. So if you see the numbers 8,15 (below), that means match a number between 8 digits and 15 digits long. I changed the code below.

    include('lib/simple_html_dom.php');
    
    $html = file_get_html('http://soundcloud.com/oembed?url=http://soundcloud.com/kiwinest/linkin-park-iridescent');
    
    preg_match_all('/[0-9]{8,15}/', $my_string, $ids);
    
    echo $ids[0];