使用PHP Simple HTML DOM Parser提取指定div内容遇阻,求解决方案
Hey there! Let's break down why your code isn't entering the foreach loop and how to extract that (+2.28%) value properly.
The Root Cause of Your Issue
Your current selector div[n_changetext] is looking for <div> elements that have an attribute named n_changetext — but your target element has an id attribute set to b_changetext. That mismatch means the parser can't find any matching elements, so the loop never runs.
Step 1: Fix the Selector to Enter the Loop
To target the correct <div>, use the id selector (since ids are unique, you can even skip the loop and grab the element directly):
// Option 1: Using id selector with foreach (though loop is unnecessary for unique id) foreach($html->find('div#b_changetext') as $e){ echo $e->innertext . '<br>'; echo "wwwwww"; // This will now show up! } // Option 2: Grab the element directly (better for unique ids) $targetDiv = $html->find('div#b_changetext', 0); if ($targetDiv) { echo $targetDiv->innertext . '<br>'; echo "wwwwww"; }
Step 2: Extract the (+2.28%) Value
The innertext includes the <span> content too, so we need to isolate just the percentage text. Here are two reliable methods:
Method 1: Use Plain Text + Regular Expression
Grab the plain text of the div and match the parenthesized percentage:
$targetDiv = $html->find('div#b_changetext', 0); if ($targetDiv) { $fullText = $targetDiv->plaintext; // Match any text inside parentheses preg_match('/\([^)]+\)/', $fullText, $matches); if (!empty($matches)) { echo $matches[0]; // Outputs: (+2.28%) } }
Method 2: Target the Text Node Directly
The percentage is a direct text child of the div. We can loop through the div's nodes to find the text node:
$targetDiv = $html->find('div#b_changetext', 0); if ($targetDiv) { foreach ($targetDiv->nodes as $node) { // Node type 3 = text node if ($node->nodetype === 3) { $percentage = trim($node->text); echo $percentage; // Outputs: (+2.28%) break; // Stop after finding the first text node } } }
Key Takeaway
Always double-check your selectors: use #id for id attributes, .class for classes, and [attribute="value"] only when targeting custom or non-id/class attributes.
内容的提问来源于stack exchange,提问作者kiranshiv

