简体   繁体   中英

Why doesn't this PHP execute?

I copied the code from this site exactly: http://davidwalsh.name/web-service-php-mysql-xml-json as follows,

/* 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);
}

And the php doesn't execute, it just displays as plain text. What's the dealio? The host supports PHP, I use it to run a Wordpress blog and other things.

There are several reasons this might be displayed as text rather than executed.

First, it is missing the <?php and ?> tags. Without these, PHP will think you simply want to send everything in this file to the browser.

If you are using Apache, you will need to tell Apache to execute the files (usually you will tell Apache to execute all files ending in .php with the PHP interpreter).

Your host may require that you put all executable files in a certain directory. Make sure you follow their instructions for setting up sites.

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

No <?php tag. Is it named as a .php file?

把它放在<?php ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM