In PHP, what is the best practice for iterating through a DOMNodeList returned by xpath::query()?
When iterating through a DOMNodeList returned by xpath::query(), it is best practice to use a foreach loop to iterate over each DOMNode in the list. This allows you to easily access and manipulate each node without having to worry about the index or length of the list.
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//div[@class="example"]');
foreach ($nodes as $node) {
// Do something with each $node
echo $node->nodeValue;
}
Keywords
Related Questions
- What function can be used in PHP to check the number of rows returned by a MySQL query and conditionally display a message?
- Are there any best practices for handling secure connections in PHP forms, especially when redirecting between http and https?
- How can I implement "Next" and "Previous" buttons in a PHP page to navigate through paginated data?