将XML字符串(节点值)放入服务器文本文件中,检索并再次回显(PHP)


Put XML string (node value) in server text file and retrieve and echo it again (PHP)

这是我的问题。我试图从一个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;
    }
?>

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

Echo调用magic方法__toString(),但serialize不允许,而且在SimpleXMLElement中不允许序列化,所以它抛出了一个Exception。但是您可以自己调用__toString()魔术方法,这就解决了您的问题。

用我的替换你的线路

$info = $xml->artist->bio->summary->__toString();