的問題的答案/標題(過濾器通過XML屬性):
您可以使用The SimpleXMLElement class:
// xml example
$foo = '<?xml version="1.0" encoding="utf-8"?>
<Root>
<File type="1">File 1</File>
<File type="2">File 2</File>
<File type="1">File 3</File>
</Root>';
$xml = new SimpleXMLElement($foo);
// get all 'File' elements with attribute 'type' = '1'
$search1 = $xml->xpath('File[@type="1"]');
// ^^^^ ^^
// Element Attribute
然後,$search1
總會有文件File 1
和File 3
。
對於OP的具體情況:沒有必要先取得所有項目。你可以這樣使用它,可以直接使用:
$result = $xml->Slides->xpath('Item[@lvl="1"]'); //get 'Item'-s with 'lvl' '1'
所以,print_r($result);
輸出:
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[file] => /upload/portfolio/22.jpg
[lvl] => 1
[designer] => 0001
[theme] => outline
)
[0] => Destiption one
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[file] => /upload/portfolio/23.jpg
[lvl] => 1
[designer] => 0002
[theme] => drawn
)
[0] => Destiption 2
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[file] => /upload/portfolio/27.jpg
[lvl] => 1
[designer] => 0003
[theme] => outline
)
[0] => Destiption 5
)
)
注意,它返回與22
,23
和27
尾部的URL(那些與lvl
= 1
)
如果你看看你的代碼,它有$result[0]->xpath...
。 $result
已經是項目的列表,所以你會得到與$result[0]
的第一項(print_r($result[0]);
):
SimpleXMLElement Object
(
[@attributes] => Array
(
[file] => /upload/portfolio/22.jpg
[lvl] => 1
[designer] => 0001
[theme] => outline
)
[0] => Destiption one
)
完整代碼(複製/粘貼運行):
$foo = '<?xml version="1.0" encoding="utf-8"?>
<Root>
<Name>Logos</Name>
<Slides>
<Item file="/upload/portfolio/22.jpg" lvl="1" designer="0001" theme="outline">Destiption one</Item>
<Item file="/upload/portfolio/23.jpg" lvl="1" designer="0002" theme="drawn">Destiption 2</Item>
<Item file="/upload/portfolio/24.jpg" lvl="2" designer="0003" theme="outline">Destiption 3</Item>
<Item file="/upload/portfolio/26.jpg" lvl="2" designer="0004" theme="drawn">Destiption 4</Item>
<Item file="/upload/portfolio/27.jpg" lvl="1" designer="0003" theme="outline">Destiption 5</Item>
<Item file="/upload/portfolio/28.jpg" lvl="3" designer="0003" theme="outline">Destiption 6</Item>
</Slides>
</Root>';
$xml = new SimpleXMLElement($foo);
$search1 = $xml->Slides->xpath('Item[@lvl="1"]');
echo '<pre>';
print_r($search1);
echo '</pre>';
謝謝你FirstOne!我還通過循環中的IF語句找到了解決方案,但您的服務器資源更簡單高效。 –
@AndrewBro,是的,我雖然循環它,但'$ result [0]'感覺有點奇怪xD。無論如何,我很樂意幫助.. – FirstOne
是的,使用$ result [0]不是最好的方法)) –