Sorry. I wasn't paying attention earlier. Your edit doesn't result in a valid Dokuwiki url.
If you are using the .htaccess form of nice urls and the 'useslash' setting, you want this:
$page = str_replace('.txt',"",$page);
$url = DOKU_URL.$page;
If you are using the internal Dokuwiki nice urls with 'useslash', you want this:
$page = str_replace('.txt',"",$page);
$url = DOKU_URL."doku.php/$page";