2010-05-07 104 views
1

我从这个网站精确复制代码:http://davidwalsh.name/web-service-php-mysql-xml-json如下,为什么不执行此PHP?

/* require the user as the parameter */ 
if(isset($_GET['user']) && intval($_GET['user'])) { 

/* soak in the passed variable or set our own */ 
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default 
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default 
$user_id = intval($_GET['user']); //no default 

/* connect to the db */ 
$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB'); 
mysql_select_db('db_name',$link) or die('Cannot select the DB'); 

/* grab the posts from the db */ 
$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts"; 
$result = mysql_query($query,$link) or die('Errant query: '.$query); 

/* create one master array of the records */ 
$posts = array(); 
if(mysql_num_rows($result)) { 
    while($post = mysql_fetch_assoc($result)) { 
     $posts[] = array('post'=>$post); 
    } 
} 

/* output in necessary format */ 
if($format == 'json') { 
    header('Content-type: application/json'); 
    echo json_encode(array('posts'=>$posts)); 
} 
else { 
    header('Content-type: text/xml'); 
    echo '<posts>'; 
    foreach($posts as $index => $post) { 
     if(is_array($post)) { 
      foreach($post as $key => $value) { 
       echo '<',$key,'>'; 
       if(is_array($value)) { 
        foreach($value as $tag => $val) { 
         echo '<',$tag,'>',htmlentities($val),'</',$tag,'>'; 
        } 
       } 
       echo '</',$key,'>'; 
      } 
     } 
    } 
    echo '</posts>'; 
} 

/* disconnect from the db */ 
@mysql_close($link); 
} 

而且PHP不执行,它只是显示为纯文本。什么是dealio?主机支持PHP,我用它来运行一个WordPress博客和其他东西。

+2

在这个问题中:'我从互联网复制了一个代码并且它不工作' – 2010-05-07 22:44:41

回答

3

有几个原因可能会显示为文本而不是执行。

首先,它缺少<?php?>标签。如果没有这些,PHP会认为您只是想将此文件中的所有内容发送到浏览器。

如果您使用的是Apache,您需要告诉Apache执行这些文件(通常您会告诉Apache执行所有以PHP解释器为结尾的.php文件)。

您的主机可能会要求您将所有可执行文件放在某个目录中。确保你按照他们的说明设置网站。

1

<?php标签。它是否被命名为.php文件?

2

尝试将所有代码包装在<?php和? >

1

把它放在<?php ?> ??

相关问题