0

这是我的问题。我正在尝试从 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 &ndash; 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;
    }
?>

但不幸的是,这并没有奏效。任何帮助将不胜感激!

4

1 回答 1

0

Echo 调用魔术方法 __toString(),但序列化没有,并且在 SimpleXMLElement 中不允许序列化,所以它抛出一个异常。但是您可以自己调用 __toString() 魔术方法,这可以解决您的问题。

用我的代替你的线

$info = $xml->artist->bio->summary->__toString();  
于 2012-07-10T11:16:59.467 回答