你想使用XPath這一點。它基本上與SimpleXML: Selecting Elements Which Have A Certain Attribute Value中概述的完全相同,但在您的情況下,您並未決定屬性值,而是根據元素值。
但是在XPath兩個你要找的是parent.So制定XPath表達式的元素是一種直截了當:
// Here we find the item element that has the child <id> element
// with node-value "12437".
list($result) = $data->xpath('(//items/item[id = "12437"])[1]');
$result->asXML('php://output');
輸出(美化):
<item>
<title>title of 12437</title>
<id>12437</id>
</item>
所以讓我們再看看這個xpath查詢的核心:
//items/item[id = "12437"]
它被寫爲:全選<item>
元素是任何<items>
元素的子元素,它們自己有一個名爲<id>
的值爲"12437"
的子元素。
現在周圍缺少的東西:
(//items/item[id = "12437"])[1]
括號周圍說:從所有這些<item>
元素,只挑了第一個。根據你的結構,這可能或可能不是必要的。
因此,這裏是完整的用法例子,online demo:
<?php
/**
* php simplexml get a specific item based on the value of a field
* @lin https://stackoverflow.com/q/17537909/367456
*/
$str = <<<XML
<items>
<item>
<title>title of 43534</title>
<id>43534</id>
</item>
<item>
<title>title of 12437</title>
<id>12437</id>
</item>
<item>
<title>title of 7868</title>
<id>7868</id>
</item>
</items>
XML;
$data = new SimpleXMLElement($str);
// Here we find the item element that has the child <id> element
// with node-value "12437".
list($result) = $data->xpath('(//items/item[id = "12437"])[1]');
$result->asXML('php://output');
那麼你所說的在您的問題標題字段是由書子元素。在搜索更復雜的xpath查詢時,請記住這一點,以便找到您要查找的內容。
這裏的heck是這個參考題嗎?它必須存在某處,但我找不到它。 – hakre