求助:如何使用SimpleHtmlDom获取文件编号与站点地址值并赋值变量
Hey David, let's work through this SimpleHtmlDom problem together— I’ve used this library plenty of times, so I’ll break down exactly how to grab those file number and site address values and assign them to variables.
Step 1: Make sure you’ve set up SimpleHtmlDom correctly
First, double-check you’ve included the library in your script:
include('simple_html_dom.php'); // Adjust the path to match where you saved the library
Step 2: Load your target HTML
You can load HTML either directly from a URL or from a string (if you’ve already fetched it elsewhere):
// Load from a URL $html = file_get_html('your-target-page-url.com'); // OR load from a pre-fetched HTML string // $html = str_get_html($your_html_content);
Step 3: Extract the values from the table
Let’s assume your table has a structure like this (super common for key-value pairs):
file number(文件编号) FN-78901 site address(站点地址) https://example.com/office-45
Here’s the code to loop through the table rows, match the labels, and assign the values to variables:
// Initialize empty variables to store our values $fileNumber = ''; $siteAddress = ''; // Loop through each table row foreach ($html->find('table tr') as $row) { // Grab all cells in the current row $cells = $row->find('td'); // Only proceed if the row has at least 2 cells (label + value) if (count($cells) >= 2) { $label = trim($cells[0]->plaintext); $value = trim($cells[1]->plaintext); // Match either the English or Chinese label to cover all cases if (str_contains($label, 'file number') || str_contains($label, '文件编号')) { $fileNumber = $value; } if (str_contains($label, 'site address') || str_contains($label, '站点地址')) { $siteAddress = $value; } } } // Test the results (remove this once you confirm it works) echo "File Number: " . $fileNumber . "<br>"; echo "Site Address: " . $siteAddress;
Quick tips to troubleshoot
- If your table uses
<th>for labels instead of<td>, replace$row->find('td')with$row->find('th, td')to capture both. - If the table has a specific ID or class (like
id="info-table"), narrow down your search to speed things up:$html->find('#info-table tr')instead oftable tr. - Use
trim()to strip extra spaces/newlines from the text— this avoids messy values with unexpected whitespace.
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

