简体   繁体   中英

Having trouble getting values from an xml file

When I try to get values it doesn't seem to work. The xml file contains multiples of the same node <post> and I thought you could call a specific node like an array, but that doesn't seem to work. Below I have included the code.

File that gets xml values:

<?php

if(file_exists('settings.xml')){
    $settings = simplexml_load_file('settings.xml');

    $site_title = $settings->title;
    $site_name = $settings->title;
    $site_stylesheet = "css/main.css";

    $theme_folder = "themes/".$settings->theme;
    if(file_exists('posts.xml')){
        $posts = simplexml_load_file('posts.xml');

        $post = $posts->post[$_GET['post']];

        $post_title = $post->title;
        $post_content = $post->content;
        $post_author = $post->author;


        include($theme_folder."/header.php");
        include($theme_folder."/post.php");
        include($theme_folder."/footer.php");
    } else {
        exit("File \"posts.xml\" does not exist!");
    }
} else {
    exit("File \"settings.xml\" does not exist!");  
}

?>

File that is included in the file above and uses the variables that the xml passes to:

<article>
    <h1><?php echo $post_title ?></h1>
    <?php echo $post_content ?>
    <p><?php echo $post_author ?></p>
</article>

Xml file:

<?xml version="1.0" encoding="utf-8"?>
<posts>
    <post>
        <title>Hello World</title>
        <author>tacticalsk8er</author>
        <content>Hello world this is my blogging site</content>
    </post>
    <post>
        <title>Hello Again</title>
        <author>Nick Peterson</author>
        <content><![CDATA[Hello Again world this is another test for my <b>blogging site</b>]]></content>
    </post>
</posts>

Of course, you can access nodes in simplexml ' array-style ':

$post = $xml->post[1]; // select second node
echo $post->title;

$xml represents the root-node <posts> , $xml->post selects posts/post .

see it working: http://3v4l.org/KOiv2

see the manual: http://www.php.net/manual/en/simplexml.examples-basic.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