PHP Simple HTML Dom提取同类多标签报错求助
Hey there, let's work through this issue together! That "Array to string conversion" error pops up because either the plaintext property is returning an unexpected array (the library can behave this way with nested elements) or you’re trying to output something that isn’t a string directly. Let’s focus on extracting exactly the three pieces of content you need, which will also resolve the error.
First, let’s recap your target: for each div.file-right, you want to grab:
- The
hrefattribute of the nested<a>tag - The plain text inside that
<a>tag (specifically the<h2>content) - The text from the three
<span>elements (page count, year, file size)
Here’s a revised, error-free code that does exactly this, with proper checks to avoid undefined property issues:
// Load the HTML (ensure $response holds your valid HTML content) $html = @str_get_html($response); // Fetch all file-right blocks $allBlocks = $html->find('div.file-right'); // Only proceed if blocks were found if ($allBlocks) { foreach ($allBlocks as $singleBlock) { // 1. Extract the <a> tag's href $linkElement = $singleBlock->find('a.ai-similar', 0); // Grab the first matching <a> $href = $linkElement ? $linkElement->href : 'No link available'; // 2. Extract the title text from the <h2> inside <a> $titleElement = $linkElement->find('h2', 0); $title = $titleElement ? $titleElement->plaintext : 'No title found'; // 3. Extract the three span elements' text $pageCount = $singleBlock->find('span.fi-pagecount', 0) ? $singleBlock->find('span.fi-pagecount', 0)->plaintext : 'No page count'; $year = $singleBlock->find('span.fi-year', 0) ? $singleBlock->find('span.fi-year', 0)->plaintext : 'No year'; $fileSize = $singleBlock->find('span.fi-size', 0) ? $singleBlock->find('span.fi-size', 0)->plaintext : 'No file size'; // Example output (you can modify this to store data instead) echo "Link: $href\n"; echo "Title: $title\n"; echo "Page Count: $pageCount\n"; echo "Year: $year\n"; echo "File Size: $fileSize\n"; echo "-------------------------\n"; } } else { echo "No file-right blocks found in the HTML."; }
Why this fixes your error:
- Instead of trying to output the entire block’s
plaintext(which might return an array due to nested elements), we target specific child elements one by one. - Using
find(selector, 0)ensures we get the first matching element (sincefind()returns an array of matches), so we’re always working with a single element object instead of an array. - Ternary checks (
$element ? $element->property : fallback) prevent errors if a child element is missing from any block.
Quick fix for your original code (if you just want the block text):
If you still wanted to output the entire block’s plaintext without errors, you can explicitly cast it to a string:
echo (string) $singleBlock->plaintext;
But extracting specific pieces is better for your use case, as it gives you full control over the data you’re collecting.
内容的提问来源于stack exchange,提问作者zish

