Reputation: 53
This is very easy i'm sure but as usual being totally thick and i'm new to SimpleXML.
All I want to do is add and or edit particular notes based on a given value. example xml file:
<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>
If I want to add an and to index how do I find the node key
I can add the content e.g.
$itemsNode = $site->page->pagename;
$itemsNode->addChild("id", '12121')->addChild('plot', 'John Doe');
but what I want/need to do is add content to pagename='index' or pagename='testit' I cannot see a way to get that (in example) index is key[0] and testit is key[1] without doing some form of foreach loop with a switch etc. There must be an easy way to do it? no?
so it should look something like this me thinks (but does not work otherwise would not bas asking question)
$paget = 'index' //(or testit')
if( (string) $site->page->pagename == $paget ){
$itemsNode = $site->page;
$itemsNode->addChild("id", '12121')->addChild('plot', 'John Doe');
}
Upvotes: 1
Views: 1680
Reputation: 1531
EDIT:
If you know the exact position of the node you can do as follows:
$site->page[0]->addChild("id", '12121');
$site->page[0]->addChild('plot', 'John Doe');
In this case page[0] would be "index" while page[1] would be "testit".
Otherwise, you should loop across the page nodes until you find the node you want. The code below shows how you can do it:
$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;
}
}
Upvotes: 1
Reputation: 20753
You can use xpath to get to the nodes you want to modify:
$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');
}
The pattern basically looks for every <pagename>
under <page>
where the <pagename>
's content is index
and steps one up to make the <page>
node returned.
Upvotes: 2