1

我敢肯定,这很容易,但像往常一样完全厚实,而且我是 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循环。必须有一种简单的方法吗?不?

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

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

$itemsNode = $site->page;

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

}
4

2 回答 2

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');
}

该模式基本上会查找's 内容所在的每个<pagename>下方,然后逐步返回以使节点返回。<page><pagename>index<page>

于 2012-08-20T15:21:16.920 回答
1

编辑:

如果您知道节点的确切位置,您可以执行以下操作:

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

在这种情况下,page[0] 将是“index”,而 page[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;
   }
}
于 2012-08-20T15:16:52.493 回答