我有一个类似于以下内容的XML:
$data = '<search-params>
<date>2013-05-20</date>
</search-params>
<results>
<date>2013-05-21 14:31:00</date>
<prices>
<for>
<players>1</players>
</for>
<amount>20</amount>
</prices>
<prices>
<for>
<players>2</players>
</for>
<amount>35</amount>
</prices>
<prices>
<for>
<players>3</players>
</for>
<amount>49.5</amount>
</prices>
<prices>
<for>
<players>4</players>
</for>
<amount>60</amount>
</prices>
</results>
<results>
<date>2013-05-21T14:40:00</date>
<prices>
<for>
<players>1</players>
</for>
<amount>20</amount>
</prices>
</results>';
现在,我想做的是根据规则删除其中一些内容。
因此,如果我有<players>
子节点4,它应该只返回具有该值的<results>
个节点。
这可以在PHP中使用吗?
我可以使用simplexml_load_string($data)
加载它。问题是如何查找信息并删除节点。
由于
答案 0 :(得分:1)
没有人回答,所以我愿意。请阅读评论。
// First, your XML must be wraped with some root tag.
$data = '<root>
<search-params>
<date>2013-05-20</date>
</search-params>
<results>
<date>2013-05-21 14:31:00</date>
<prices>
<for>
<players>1</players>
</for>
<amount>20</amount>
</prices>
<prices>
<for>
<players>2</players>
</for>
<amount>35</amount>
</prices>
<prices>
<for>
<players>3</players>
</for>
<amount>49.5</amount>
</prices>
<prices>
<for>
<players>4</players>
</for>
<amount>60</amount>
</prices>
</results>
<results>
<date>2013-05-21T14:40:00</date>
<prices>
<for>
<players>1</players>
</for>
<amount>20</amount>
</prices>
</results>
</root>';
// Instancing the SimpleXMLElement within the XML(obviously)
$xml = new SimpleXMLElement($data);
// XPath
$xpath = $xml->xpath("results[prices/for[contains(players,'4')]]");
/**
* eXplained XPath:
* <results> that
* <prices>/<for>
* contains <players> that content is equal 4
*/
foreach($xpath as $node){
// just for fun echoes the <results> node
echo $node->asXml();
}