Parsing HTML Tables Without External Libraries
The core issue preventing your script from populating the array isn't the parseTable() logic itself; it is how you are retrieving and sanitizing the raw HTML. The snippet provided relies on file_get_contents('http://flow935.com/playlist/flowhis.HTM') to fetch the source. While this works for simple local files, fetching remote URLs directly in PHP often triggers a silent failure due to SSL verification defaults or missing headers required by some servers. If file_get_contents() returns false, passing that value into your regex parser results in an empty match, which explains the empty array output.
To resolve this, you must explicitly handle the HTTP request using cURL. This approach gives you granular control over SSL verification and User-Agent headers, preventing many servers from blocking the request. Here is a robust implementation:
$url = 'http://flow935.com/playlist/flowhis.HTM';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false, // Use only for non-production environments or test domains
CURLOPT_USERAGENT => 'Mozilla/5.0'
]);
$html = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Basic validation before parsing
if ($httpCode !== 200 || $html === false) {
throw new Exception("Failed to fetch URL: " . $httpCode);
}
Once the data is successfully retrieved and stored in $html, you can proceed with the parsing logic. The original code uses regular expressions to extract table content, which is a viable strategy for static HTML structures but requires strict attention to delimiters. Your specific regex patterns like /<table.*?>/s use the dot-star (.) character combined with line-ending modifiers. These patterns assume that the HTML source does not contain newlines within tags or that the tag structure is perfectly closed, which often isn't the case in real-world HTML generated by browsers.
A more reliable strategy involves using a DOM parser like DOMDocument. This library handles nested tags, malformed attributes, and whitespace stripping automatically, reducing the risk of regex backtracking errors. However, if you must stick to pure regex for performance or environment constraints, ensure that the source HTML is cleaned first. You might use preg_replace to normalize whitespace around tags before running your extraction logic.
Regarding the output structure, your goal is a multi-dimensional array where keys correspond to header cells and values correspond to data cells in the same row. The provided regex loop attempts to map $row_headers[$i] to every <td> found in the row. This approach assumes a strict column count between headers and data rows. If a data row has fewer or more columns than the header row, this direct mapping will misalign values or create empty keys.
In your specific example, the headers appear to be 1, 2, 3. The data rows contain time, artist name, and song title. If the HTML source uses <th> for the first row and <td> for subsequent rows, your current regex alternates between matching these tags. A potential pitfall is that if a header row contains merged cells (colspan), the simple iteration will break. For production-grade parsing, always validate that the number of extracted data points matches the expected schema before assigning keys.
For developers working within the Laravel ecosystem, you might consider using packages like symfony/dom-crawler or leveraging built-in helpers if the application architecture supports it. However, for standalone scripts, cURL combined with careful regex validation remains a lightweight solution. If you are dealing with complex tables that require dynamic class handling, you should inspect the specific HTML structure of the target URL to see if CSS classes can distinguish headers from data cells, allowing for more resilient parsing logic than raw text extraction.
Always remember that file_get_contents without proper error checking is a common source of silent failures in production scripts. By switching to cURL and validating the HTTP response code, you ensure that your parser only attempts to process valid content.