Q:

Simplexml_load_file breaks if link comes from Drupals field_link

I am trying to dynamically load a KML-File from Google Maps, that the user can configure over an input field in Drupal (Link field). However I am stuck, since the following works flawlessly, but the last one does not.
Works:
$xml = simplexml_load_file("Google Maps Link");

Works as well:
$link = "Google Maps Link";
$xml = simplexml_load_file($link);

Does not work:
$link = $fields['field_link']->content;
// produces "
//           http://www....."
$xml = simplexml_load_file($link);

I don't really know what is going on here. I tried to use trim() or htmlspecialchars() (to see any weird char), but nothing worked so far. I only get the error Fatal error: Call to a member function asXML() on a non-object but this is just due to the fact that the xml does not get loaded. simplexml_load_file returns false. When I print the two links, then they are identical. The only thing I see is that the link from Drupal has some char at the beginning that forces it into a new line. Don't know how to identify it though.

A:

Remove unidentified (and unspecified) whitespace from your link using preg_replace and \s, which represents any whitespace character:
$link = '
            http://www.example.com';

$link = preg_replace("/\s+/", "", $link);
echo ">" . $link . "<" . PHP_EOL;

Output:
>http://www.example.com<

You should now be able to load it using simplexml_load_file($link);.

