SimpleXML查找父节点密钥

时间:2012-08-20 15:04:32

标签: php simplexml

这很容易,我很确定,但像往常一样厚,我是SimpleXML的新手。

我想要做的就是根据给定的值添加和/或编辑特定的笔记。示例xml文件:

<site>
    <page>
     <pagename>index</pagename>
      <title>PHP: Behind the Parser</title>
      <id>abc
      <plot>
       So, this language. It's like, a programming language. Or is it a
       scripting language? All is revealed in this thrilling horror spoof
       of a documentary.
      </plot>
      </id>
      <id>def
      <plot>
      2345234 So, this language. It's like, a programming language. Or is it a
       scripting language? All is revealed in this thrilling horror spoof
       of a documentary.
      </plot>
      </id>
    </page>

     <page>
      <pagename>testit</pagename>
      <title>node2</title>
      <id>345
      <plot>
       345234 So, this language. It's like, a programming language. Or is it a
       scripting language? All is revealed in this thrilling horror spoof
       of a documentary.
      </plot>
      </id>
    </page>
    </site>

如果我想添加和索引如何找到节点密钥

我可以添加内容,例如

$itemsNode = $site->page->pagename;

$itemsNode->addChild("id", '12121')->addChild('plot', 'John Doe');

但是我想要/需要做的是将内容添加到pagename ='index'或pagename ='testit'我看不到得到它的方法(例如)index是key [0]而testit是key [1没有用开关等做某种形式的foreach循环。必须有一个简单的方法来做到这一点?没有?

所以它应该看起来像我认为的那样(但不起作用,否则不会问问题)

$paget = 'index' //(or testit')
if( (string) $site->page->pagename == $paget ){

$itemsNode = $site->page;

$itemsNode->addChild("id", '12121')->addChild('plot', 'John Doe');

}

2 个答案:

答案 0 :(得分:2)

您可以使用xpath访问要修改的节点:

$xml_string = '<site>...'; // your original input
$xml = simplexml_load_string($xml_string);
$pages = $xml->xpath('//page/pagename[text()="index"]/..')
if ($nodes) {
    // at least one node found, you can use it as before
    $pages[0]->addChild('id', '12121');
}

该模式基本上会查找<pagename>内容为<page>的{​​{1}}下的每个<pagename>,并在步骤1中返回index个节点

答案 1 :(得分:1)

编辑:

如果您知道节点的确切位置,可按以下步骤操作:

$site->page[0]->addChild("id", '12121');
$site->page[0]->addChild('plot', 'John Doe');

在这种情况下,页面[0]将是“索引”,而页面[1]将是“testit”。

否则,您应该遍历页面节点,直到找到所需的节点。下面的代码显示了如何执行此操作:

$paget = "index";
foreach( $site->page as $page ) {
   if( $page->pagename == $paget ) {
     // Found the node
     // Play with $page as you like...
     $page->addChild("id", '12121');
     $page->addChild('plot', 'John Doe');
     break;
   }
}