-1

我有一个如下所示的 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). 问题是如何找到信息并删除节点。

谢谢

4

1 回答 1

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();
}
于 2013-05-21T14:28:36.520 回答