2013-11-15 102 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