带有XML-Url中特殊字符的simpleXML

时间:2013-05-04 10:45:50

标签: encoding utf-8 simplexml

我的代码有点问题。我试图从Spotify中提取歌曲ID。 这对我来说很好,但不适用于网址中的特殊字符(如ü,ö,ä)。

我收到此警告(第一行是回显的Url):

http://ws.spotify.com/search/1/track?q=Sportfreunde+Stiller+AND+track:Frühling
Warning: SimpleXMLElement::__toString() [simplexmlelement.--tostring]: Node no longer exists in /Applications/AMPPS/www/spotify.php on line 28

这是我的代码:

function getID($artist,$title){

$url = utf8_decode("http://ws.spotify.com/search/1/track?q=".$artist."+AND+track:".$title);
echo $url;
    $xml = simplexml_load_file($url);
    $id= $xml->track->attributes();
    return($id);

 }

echo getID("Sportfreunde+Stiller","Frühling");

如何解决这个问题?我尝试了utf_encode(),但这没有用。

谢谢!

1 个答案:

答案 0 :(得分:0)

这与UTF-8编码无关,当然也不是命名错误的utf8_decode / utf8_encode函数,它们应该真正命名为utf8_to_iso8859_1 / iso8859_1_to_utf8,并且很少是任何编码问题的正确答案。

严格来说,网址只能包含一组非常有限的字符 - 基本字母,数字和一些标点符号。必须使用%3f等序列对其他任何内容进行转义。

要正确转义URL中的字符串,可以使用PHP函数urlencode(),例如

$url = "http://ws.spotify.com/search/1/track?q=" . urlencode($artist) . "+AND+track:" . urlencode($title);
相关问题