2013-11-15 77 views
0

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

文件获取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> 

回答

0

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

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

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

看到它的工作:http://3v4l.org/KOiv2

看到手册: '?post.php中后期= 0' http://www.php.net/manual/en/simplexml.examples-basic.php

+0

为什么然后当我通过像一个URL它不工作? – tacticalsk8er

+0

@ tacticalsk8er:尝试'$ id = intval($ _ GET ['post']); $ post = $ xml-> post [$ id];' – michi

+0

工作正常!是因为当你传递'$ _GET'时,你实际上传递了一个字符串? – tacticalsk8er