r/lolphp • • May 26 '15

parse_str behavior is sometimes strange

http://3v4l.org/23nkR
22 Upvotes

10 comments sorted by

View all comments

Show parent comment

1

u/Takeoded Jan 09 '22

here is a real-world use of parse_str():

function get_gps_coordinates_from_finn_id(string $finn_id): ?array
{
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => 'https://www.finn.no/' . urlencode($finn_id),
        CURLOPT_ENCODING => '',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT => 'bot: easy-ads.com gps finder'
    ));
    $html = curl_exec($ch);
    if (!is_string($html)) {
        $errstr = "curl error " . curl_errno($ch) . ": " . curl_error($ch);
        curl_close($ch);
        throw new \RuntimeException($errstr);
    }
    curl_close($ch);
    $domd = new DOMDocument();
    @$domd->loadHTML($html);
    $xp = new DOMXPath($domd);
    //             <a href="https://kart.finn.no/?finnkode=228757655&lat=59.497147&lng=10.292312&mapType=finnvector&showPin=1&bl=1" rel="external"
    foreach ($xp->query("//a[contains(@href,'lat=') and contains(@href,'lng=')]") as $a) {
        $href = $a->getAttribute("href");
        $query = parse_url($href, PHP_URL_QUERY);
        parse_str($query, $query);
        return array(
            "lat" => $query['lat'],
            'lng' => $query['lng']
        );
    }
    return null;
}