无法从xml文件中获取值

时间:2013-11-15 20:04:13

标签: php xml simplexml

当我尝试获取值时,它似乎不起作用。 xml文件包含同一节点<post>的多个,我认为你可以像一个数组一样调用一个特定的节点,但这似乎不起作用。下面我已经包含了代码。

获取xml值的文件:

<?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!");  
}

?>

上面文件中包含的文件,并使用xml传递给的变量:

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

Xml文件:

<?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>

1 个答案:

答案 0 :(得分:0)

当然,您可以访问simplexml'array-style'中的节点:

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

$xml代表根节点<posts>$xml->post选择posts/post

看到它有效:http://3v4l.org/KOiv2

请参阅手册:http://www.php.net/manual/en/simplexml.examples-basic.php