SimpleXML查找父节点键


SimpleXML find parent node key

我相信这很容易,但和往常一样,这是完全厚的,而且我是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'。如果不使用开关等进行某种形式的foreach循环,我看不出有什么方法可以获得(例如)index is key[0]和testit is key[1]?不

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

$paget = 'index' //(or testit')
if( (string) $site->page->pagename == $paget ){
$itemsNode = $site->page;
$itemsNode->addChild("id", '12121')->addChild('plot', 'John Doe');
}

您可以使用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');
}

该模式基本上查找<page>下的每个<pagename>,其中<pagename>的内容是index,并逐步递增一步以返回<page>节点。

编辑:

如果你知道节点的确切位置,你可以做如下:

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

在这种情况下,页面[0]将是"index",而页面[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;
   }
}