2011-11-25 41 views
3

假設我有這個XML文件。PHP閱讀XML與Where子句

<book> 
    <id>1</id> 
    <title>Harry Potter - bla bla bla</title> 
    <author>J.K Rowling</author> 
</book> 
<book> 
    <id>2</id> 
    <title>Other book</title> 
    <author>A Name</author> 
</book> 

有沒有一種方法,我可以通過PHP讀取並獲得#2 ID,或者我必須使用IF? 像jQuery選擇 ':公式(2)',或MySQL 'WHERE id = 2'

+0

什麼actualy,我不知道這樣做,搜索並沒有取得成功。 – BernaMariano

+2

xpath:// book [id =「2」] – Gordon

+1

旁註:在子元素中使用id可能不是最好的主意。 ''(+也許將'id'定義爲類型(ID)的屬性)將是更可取的。 – VolkerK

回答

2

如果你想要的僅僅是第二個,你可以使用DOM。這很簡單。

$dom->loadXML(<<<XML 
<book> 
    <id>1</id> 
    <title>Harry Potter - bla bla bla</title> 
    <author>J.K Rowling</author> 
</book> 
<book> 
    <id>2</id> 
    <title>Other book</title> 
    <author>A Name</author> 
</book> 
XML;); 

$book=$dom->getElementsByTagName('book')->item(1); 

編輯:我剛纔看到你說你正在尋找第二個ID,而不是第二個元素,你需要爲XPath的。

$xml=new SimpleXMLElement(<<<XML 
<book> 
    <id>1</id> 
    <title>Harry Potter - bla bla bla</title> 
    <author>J.K Rowling</author> 
</book> 
<book> 
    <id>2</id> 
    <title>Other book</title> 
    <author>A Name</author> 
</book> 
XML;); 
$result=$xml->xpath('/book[id=2]'); 

更多的XPath here

3

有,嘗試PHP的SimpleXML的解析器:http://php.net/manual/en/book.simplexml.php

+0

請詳細說明 –

+0

蓮蓬頭做了,旁邊這不是給人們沒有他們提供一些輸入的人的目標。如果他嘗試了一些東西併發布代碼,並表示它仍然沒有解決,我會:)。 – Wesley

+1

夠公平:) +1 –