How can the issue of "Cannot add element page number 2 when only 0 such elements exist" be addressed in PHP when dealing with XML navigation structures?

Issue: The error "Cannot add element page number 2 when only 0 such elements exist" occurs when trying to navigate to a page number that does not exist in an XML structure. To address this, we need to check if the requested page number exists before attempting to navigate to it. PHP Code Snippet:

// Assuming $xml is the XML navigation structure
$totalPages = count($xml->page);
$pageNumber = 2; // Example page number

if ($pageNumber <= $totalPages) {
    // Navigate to page number 2
    $currentPage = $xml->page[$pageNumber - 1];
    // Add your logic to work with the current page
} else {
    echo "Error: Page number $pageNumber does not exist.";
}