你的XML是無效的,封閉根元素不匹配,並且Type
元素被封閉,type
。 XML區分大小寫。
Xpath工作使用位置路徑和條件位置路徑是從當前上下文到元素的分層路徑。他們返回一個節點列表。該列表可以使用條件進行過濾。
SimpleXMLElement對象有一個方法xpath()
在關聯節點的上下文中執行表達式。
$xml = <<<'XML'
<Files>
<data id="1">
<type>Flower</type>
</data>
<data id="2">
<type>Flower</type>
</data>
<data id="3">
<type>Flower</type>
</data>
<data id="4">
<type>Flower</type>
</data>
</Files>
XML;
$files = new SimpleXMLElement($xml);
$target = new SimpleXMLElement('<select/>');
foreach ($files->xpath('data[type = "Flower"]') as $data) {
echo '.';
$option = $target->addChild('option', $data['id']);
$option['value'] = $data['id'];
}
echo $target->asXml();
你不應該創建你的XML文本。爲它使用XML Api。
DOM更加具體和強大。例如,您可以將創建的DOM序列化爲HTML。
$source = new DOMDocument();
$source->loadXml($xml);
$xpath = new DOMXpath($source);
$target = new DOMDocument();
$select = $target->appendChild($target->createElement('select'));
foreach ($xpath->evaluate('/Files/data[type = "Flower"]') as $data) {
$option = $select->appendChild($target->createElement('option'));
$option->setAttribute('value', $data->getAttribute('id'));
$option->appendChild($target->createTextNode($data->getAttribute('id')));
}
echo $target->saveHtml($select);
來源
2016-12-30 18:33:01
ThW
謝謝選擇作爲答案,因爲它比以前的答案更簡單!雖然兩者都很好。 –