user2928990
user2928990

Reputation: 11

url encoding returns unwanted characters

I am trying to encode a base url; the problem is I am getting unwanted characters at the end of each url. Can you help me debug my code in removing these characters?

<?php

$names = file('query-file.txt');
$baseUrl = 'whois.whoisxmlapi.com/';
foreach($names as $name) {
    $url = $baseUrl . urlencode($name);
    $record = rtrim($url);
    echo $record.'<br>';
}

?>

output

whois.whoisxmlapi.com/google.com%0D%0A
whois.whoisxmlapi.com/cnn.com%0D%0A
whois.whoisxmlapi.com/msn.com%0D%0A
whois.whoisxmlapi.com/hotmail.com%0D%0A
whois.whoisxmlapi.com/yahoo.com%0D%0A
whois.whoisxmlapi.com/gmail.com

Upvotes: 0

Views: 94

Answers (2)

Andr&#233; Laszlo
Andr&#233; Laszlo

Reputation: 15537

Each line in your file ends with "\r\n" (hexadecimal values 0xD and 0xA), also known as windows newlines.

Use the FILE_IGNORE_NEW_LINES flag on the call to file(), which will simply exclude the newlines:

$names = file('query-file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Or use the rtrim() function on each line to get rid of the trailing whitespace, before encoding it:

$url = $baseUrl . urlencode(rtrim($name));

Upvotes: 1

dev4092
dev4092

Reputation: 2891

you used encode that's why unwanted characters came. try urldecode instead of urlencode may be this one is helpful to you :-)

Upvotes: 0

Related Questions