Url Parsing in PHP

Here’s the PHP translation of the URL parsing example:

<?php

// URLs provide a uniform way to locate resources.
// Here's how to parse URLs in PHP.

// We'll parse this example URL, which includes a
// scheme, authentication info, host, port, path,
// query params, and query fragment.
$s = "postgres://user:pass@host.com:5432/path?k=v#f";

// Parse the URL and ensure there are no errors.
$u = parse_url($s);
if ($u === false) {
    throw new Exception("Failed to parse URL");
}

// Accessing the scheme is straightforward.
echo $u['scheme'] . "\n";

// User info contains all authentication info; we need to
// parse it separately for individual username and password.
echo $u['user'] . ":" . $u['pass'] . "\n";
echo $u['user'] . "\n";
echo $u['pass'] . "\n";

// The host contains both the hostname and the port,
// if present. We can access them separately.
echo $u['host'] . ":" . $u['port'] . "\n";
echo $u['host'] . "\n";
echo $u['port'] . "\n";

// Here we extract the path and the fragment after
// the #.
echo $u['path'] . "\n";
echo $u['fragment'] . "\n";

// To get query params in a string of k=v format,
// use the 'query' key. You can also parse query params
// into an array.
echo $u['query'] . "\n";
parse_str($u['query'], $queryParams);
print_r($queryParams);
echo $queryParams['k'] . "\n";

Running our URL parsing program shows all the different pieces that we extracted.

$ php url-parsing.php
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
Array
(
    [k] => v
)
v

In this PHP version:

  1. We use the built-in parse_url() function to parse the URL.
  2. The parsed URL components are returned in an associative array.
  3. We access individual components using array keys.
  4. For query parameters, we use parse_str() to convert the query string into an array.
  5. Error handling is done using exceptions instead of panics.
  6. We use echo for output instead of fmt.Println().

The structure and functionality closely mirror the original example, adapted to PHP’s syntax and standard library functions.