idk
idk

Reputation: 53

PHP simpleXML: Read XML, add node and save

I'm having some problems with adding a xml node to its parent. I receive variables $cat, $title and $isbn. I want to parse $title and $isbn to an XML node and add it to the right categorie ($cat). die(var_dump($parent)); --> returns NULL, so the biggest problem (I think) is that I can't figure out how to add my node to the right parent because I cant get it identified. Any suggestions?

The XML file:

<?xml version="1.0"?>
<books version="1.0">
  <categorie name="catone" id="100">
    <book title="1_WS2012" isbn="isbnone" />
    <book title="1W2012DHCP" isbn="ibsntwo" />
  </categorie>
  <categorie title="cattwo" id="101">
    <book title="2W2008R2DC" isbn="isbnthree" />
  </categorie>
  <categorie title="catthree" id="103">
    <book title="3SBS" isbn="isbnfout=" />
  </categorie>
</books>

The Code:

//Get variables
$cat = "catone";
$title = "testtitle";
$isbn = "testisbn";

$xmlDoc = simplexml_load_file("books.xml");
$parent = null;

//Construct node
$childstring = "<book></book>";
$child = new SimpleXMLElement($childstring);
$child->addAttribute('title', $title);
$child->addAttribute('isbn', $isbn);
//This works (results in <book title="testtile" isbn="testisbn" />)

//Add node to correct parent
for ($i=0; $i <= sizeof($xmlDoc->categorie) -1; $i++) {

  //The condition does also work
  if (strtoupper($xmlDoc->categorie[$i]->attributes()->name) == strtoupper($cat))
  {
    //I'm stuck here
    $parent = $xmlDoc->categorie[$i]->attributes()->xpath('/object/data[@type="me"]');;
    $xmlDoc->$parent->addChild($child);
  } 
}

//Write file
file_put_contents("books.xml", $xmlDoc->asXML());

Desired result:

<books version="1.0">
  <categorie name="catone" id="100">
    <book title="1_WS2012" isbn="isbnone" />
    <book title="1W2012DHCP" isbn="ibsntwo" />
    <book title="testtitle" isbn"testisbn" /> 
  </categorie>
  <categorie title="cattwo" id="101">
    <book title="2W2008R2DC" isbn="isbnthree" />
  </categorie>
  <categorie title="catthree" id="103">
    <book title="3SBS" isbn="isbnfout=" />
  </categorie>
</books>

Upvotes: 1

Views: 224

Answers (1)

michi
michi

Reputation: 6625

First, use xpath to select the parent. xpath is like SQL for XML:

$xml = simplexml_load_string($x); // assume XML in $x
$parent = $xml->xpath("/books/categorie[@name = 'catone']")[0];

Note: The above code requires PHP >= 5.4 for the [0] at the end of line 2. (1)

Now, add the new <book> and its attributes:

$new = $parent->addChild("book","");
$new->addAttribute("title", "testtitle");
$new->addAttribute("isbn", "testisbn");

see it working: https://eval.in/131009

(1) if you are on PHP < 5.4, either update or do:

$parent = $xml->xpath("/books/categorie[@name = 'catone']");
$parent = $parent[0];

Upvotes: 2

Related Questions