2009-09-25 47 views
0

我是新来的PHP,这可能是一个愚蠢的问题要问,所以不投我失望,只是因为我不懂的东西......PHP使用simplexml_load_file

php -r "print_r(simplexml_load_file('http://twitter.com/statuses/user_timeline/31139114.rss'));" 

让我们这对一个例子,通过运行这个命令我得到(在屏幕上)XML输出。

我的问题是有可能保存这些数据,而不只是屏幕上,但在一个文件中,然后读取该文件,并有确切一样的,如果你已经做出使用simplexml_load_file()

回答

6

您也可以下载数据,使用类似file_get_contents;它会在一个PHP字符串中为您提供整个XML。
例如:

$xml = file_get_contents('http://twitter.com/statuses/user_timeline/31139114.rss'); 

$xml现在包含XML字符串。


然后,您可以使用file_put_contents将该字符串写入文件。
例如:

file_put_contents('/home/squale/developpement/tests/temp/test.xml', $xml); 

而且,检查文件,在命令行:

$ cat test.xml                                                 
<?xml version="1.0" encoding="UTF-8"?>                                           
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">                                      
    <channel>                                                  
    <title>Twitter/eBayDailyDeals</title>                                          
    <link>http://twitter.com/eBayDailyDeals</link>                                        
    <atom:link type="application/rss+xml" href="http://twitter.com/statuses/user_timeline/31139114.rss" rel="self"/>                        
    <description>Twitter updates from eBay Daily Deals/eBayDailyDeals.</description>                               
    <language>en-us</language>                                             
    <ttl>40</ttl>                                                 
    <item> 
... 
... 


之后,您可以使用simplexml_load_file从文件中读取。
例如:

$data = file_get_contents('/home/squale/developpement/tests/temp/test.xml'); 

而且$data现在包含的XML字符串;-)


考虑到你从远程服务器获取XML是一个字符串,无需序列化;和file_put_contents更容易fopen + fwrite + fclose ;-)

+0

我一直对你的答案的质量和细节印象深刻。 – 2009-09-25 20:33:58

+0

因此为什么15k代表 – alexus 2009-09-25 21:12:51

+0

@Franck:谢谢! @Alexus:也谢谢:-) – 2009-09-25 21:49:09