这是我的问题。我正在尝试从XML url(来自last.fm api)检索值。例如,艺术家的传记。
我已经知道我可以这样做(例如对于阿黛尔):
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
echo $info;
?>
返回:
Adele Laurie Blue Adkins, (born 5 May 1988), is a Grammy Award-Winning English <a href="http://www.last.fm/tag/singer-songwriter" class="bbcode_tag" rel="tag">singer-songwriter</a> from Enfield, North London. Her debut album, <a title="Adele - 19" href="http://www.last.fm/music/Adele/19" class="bbcode_album">19</a>, was released in January 2008 and entered the UK album chart at #1. The album has since received four-times Platinum certification in the UK and has sold 5,500,000 copies worldwide. The album included the hugely popular song <a title="Adele – Chasing Pavements" href="http://www.last.fm/music/Adele/_/Chasing+Pavements" class="bbcode_track">Chasing Pavements</a>. 19 earned Adele two Grammy Awards in February 2009 for Best New Artist and Best Female Pop Vocal Performance.
我现在想把结果放在一个文本文件中并将其存储在我网站上的文件夹中,例如:“http://mysite.com/artistdescriptions/adele.txt”。
我已经尝试过了:
<?php
$file_path = $_SERVER['DOCUMENT_ROOT'].'/artistdescriptions/adele.txt';
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
file_put_contents($file_path, serialize($info));
$file_contents = file_get_contents($file_path);
if(!empty($file_contents)) {
$data = unserialize($file_contents);
echo $data;
}
?>
但遗憾的是,这并没有奏效。任何帮助将不胜感激!
答案 0 :(得分:0)
Echo调用魔术方法__toString(),但序列化没有,并且在SimpleXMLElement中不允许序列化,因此抛出异常。但你可以自己调用__toString()魔术方法,这可以解决你的问题。
用我的替换你的行
$info = $xml->artist->bio->summary->__toString();