2011-08-22 72 views
2

我有一個列表,包括尋找像這樣的鏈接:我可以使用php包含xml文件中的元素嗎?

<a href=index.php?p=page_1>Page 1</a> 
<a href=index.php?p=page_2>Page 2</a> 
<a href=index.php?p=page_3>Page 3</a> 

當點擊它們包括網頁(page_1.inc.php或page_2.inc.php或page_3.inc.php)我的網頁上感謝對此腳本:

<?php 
    $pages_dir = 'pages'; 

    if(!empty($_GET['p'])){ 
     $pages = scandir($pages_dir, 0); 
     unset($pages[0], $pages[1]); 

     $p = $_GET['p']; 

     if (in_array($p.'.inc.php', $pages)){ 
      include ($pages_dir.'/'.$p.'.inc.php'); 
     } 
     else { 
      echo 'Sorry, could not find the page!'; 
     } 
    } 
    else { 
     include($pages_dir.'/home.inc.php'); 
    } 
?> 

期間。
我也有一個XML文件看起來像這樣:

<program> 
    <item> 
     <date>27/8</date> 
     <title>Page 1</title> 
     <info>This is info text</info> 
    </item> 
    <item> 
     <date>3/9</date> 
     <title>Page 2</title> 
     <info>This is info text again</info> 
    </item> 
    <item> 
     <date>10/9</date> 
     <title>Page 3</title> 
     <info>This just some info</info> 
    </item> 
</program> 

這就是我想要達到的目標:
如果我點擊鏈接「1」,它會顯示在「這是信息文本」上這一頁。
如果我點擊「頁面2」鏈接,它會在頁面上顯示「這是信息文本」。
如果我點擊鏈接「第3頁」,它會在頁面上顯示「This just some info」。

我清楚了嗎? 有沒有解決方法?

+1

是的,這是可能的。有一個簡單的解決方案。如果沒有人很快發帖,我會回到這個。 – cwallenpoole

回答

3

您應該可以使用xpath()方法與SimpleXMLElement一起執行此操作。

$xmlString = file_get_contents("path/to/xml/file.xml"); 
$xml = new SimpleXMLElement($xmlString); 
$info = $xml->xpath("/program/item[title='Page " . $page . "']/info"); 
echo (string) $info[0]; 

更新:

要獲得所有日期的數組,你會做這樣的事情:

$xmlString = file_get_contents("path/to/xml/file.xml"); 
$xml = new SimpleXMLElement($xmlString); 
$results = $xml->xpath("/program/item/date"); 

$dates = array(); 
if (!empty($results)) { 
    foreach ($results as $date) { 
     array_push($dates, (string) $date); // It's important to typecast from SimpleXMLElement to string here 
    } 
} 

此外,您還可以結合邏輯,如果需要的話,從第一和第二個例子。您可以重複使用$xml對象進行多個XPath查詢。

如果您需要$dates是唯一的,你可以做array_push()前添加一個in_array()檢查,也可以在foreach後使用array_unique()

+0

好的...因爲我是PHP新手,想要學習它,不只是使用它,讓我們看看我是否理解! 兩個第一行用SimpleXMLElement函數讀取xml文件的內容,對吧? 第三行設置$ info,將元素「info」作爲「item」的字符串讀取,並顯示$ page。 最後一行打印$ info。 我對不對? – lindhe

+1

@ Lindhe94無後顧之憂。我曾經是PHP新手。是的,前兩行是正確的。第三行是使用XPath(我建議你閱讀它)來掃描'$ xml'變量中包含的XML。該xpath查詢正在過濾到我們關心的XML節點。它從'program'開始,然後轉到所有'item',然後限制'item'返回具有節點'title'的文本「Page 1」,「Page 2」等。最後,它選擇這個上下文中的info信息節點。 'info'節點中的文本作爲數組返回到'$ info',我們只選擇第一個索引(只有一個結果)。 –

+0

噢,另外一個問題就是...... 當我把這個插入到我的代碼中時,我會在上面的代碼中創建一個elseif語句來指定它將被打印的時間。 我需要做一些類似於if語句的事情。我可以以某種方式製作所有日期的數組並使用in_array函數嗎?如果是這樣的話:我該如何創建這個數組? – lindhe

相關問題