Solved

PHP and SimpleXML

Posted on 2014-11-11
17
75 Views
Last Modified: 2014-11-17
I'm new to SimpleXML as is so often is the case it's a steep learning curve.

I have an XML file groups1.xml:-

<?xml version='1.0' encoding='UTF-8'?>
<KeywordData>
  <KeywordGroups>
    <Group>Activity</Group>
    <Group>Cohort</Group>
    <Group>Years</Group>
    <Group>Names</Group>
    <Group>Flags</Group>
  </KeywordGroups>
  <Keywords>
    <Activities>
        <Activity>505</Activity>
        <Activity>448</Activity>
        <Activity>455</Activity>
    </Activities>
    <Cohorts>
        <Cohort>423</Cohort>
        <Cohort>413</Cohort>
        <Cohort>494</Cohort>
    </Cohorts>
  </Keywords>
</KeywordData>

Open in new window

I'm trying to add a new node to Activities using addchlld:-

$array = simplexml_load_file('groups1.xml');
print '<pre>';
print_r($array);
print '</pre>';
$keyword = $array->Keywords->Activities->addChild('Activity');

Open in new window


... but however I try it fails to work even though the array prints just fine. Can anyone help?
0
Comment
Question by:cescentman
  • 9
  • 7
17 Comments
 
LVL 14

Expert Comment

by:Dzynit
ID: 40435840
Did you try testing it without the print commands? I found that trying to echo or print any php in the mix of the xml, the xml display fails.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40436406
This is a fairly common issue, and the reason it's troublesome goes to the differences in PHP variables and references.  You really need to understand this difference because it can haunt all of your work with object-oriented PHP!
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html

Try it this way:
http://iconoun.com/demo/temp_cescentman.php

<?php // demo/temp_cescentman.php
error_reporting(E_ALL);
echo '<pre>';

$xml = <<<EOD
<?xml version='1.0' encoding='UTF-8'?>
<KeywordData>
  <KeywordGroups>
    <Group>Activity</Group>
    <Group>Cohort</Group>
    <Group>Years</Group>
    <Group>Names</Group>
    <Group>Flags</Group>
  </KeywordGroups>
  <Keywords>
    <Activities>
        <Activity>505</Activity>
        <Activity>448</Activity>
        <Activity>455</Activity>
    </Activities>
    <Cohorts>
        <Cohort>423</Cohort>
        <Cohort>413</Cohort>
        <Cohort>494</Cohort>
    </Cohorts>
  </Keywords>
</KeywordData>
EOD;

// LOAD THE XML STRING INTO AN OBJECT
$obj = SimpleXML_Load_String($xml);

// ACTIVATE THIS TO SEE THE OBJECT
// var_dump($obj);

$act = $obj->Keywords->Activities->Activity;
$act[] = 'New Thing added to the Activity array of Activities';
var_dump($obj);

Open in new window

0
 
LVL 1

Author Comment

by:cescentman
ID: 40439564
Thanks both

@Ray Paseur I was trying to work out how to use the addchild method. Not sure how this relates to that?

@Dzynit I will try that and see.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40443561
Why do you want to use addChild()?  What do you expect it to do for you?
0
 
LVL 1

Author Comment

by:cescentman
ID: 40444432
I was expecting it to add a node as I say above. As to why well I'm experimenting.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40444455
AddChild() is the wrong tool here.  We're looking at an array inside the object.  You don't use addChild() to add elements to an array, just use the array notation.

object(SimpleXMLElement)#1 (2) {
  ["KeywordGroups"]=>
  object(SimpleXMLElement)#2 (1) {
    ["Group"]=>
    array(5) {
      [0]=>
      string(8) "Activity"
      [1]=>
      string(6) "Cohort"
      [2]=>
      string(5) "Years"
      [3]=>
      string(5) "Names"
      [4]=>
      string(5) "Flags"
    }
  }
  ["Keywords"]=>
  object(SimpleXMLElement)#5 (2) {
    ["Activities"]=>
    object(SimpleXMLElement)#6 (1) {
      ["Activity"]=>
      array(3) { /** <----- NOTE THAT THIS IS NOT AN OBJECT -- IT IS AN ARRAY */
        [0]=>
        string(3) "505"
        [1]=>
        string(3) "448"
        [2]=>
        string(3) "455"
      }
    }
    ["Cohorts"]=>
    object(SimpleXMLElement)#7 (1) {
      ["Cohort"]=>
      array(3) {
        [0]=>
        string(3) "423"
        [1]=>
        string(3) "413"
        [2]=>
        string(3) "494"
      }
    }
  }
}

Open in new window

0
 
LVL 1

Author Comment

by:cescentman
ID: 40444510
This what confuses me as the PHP manual:-

http://php.net/manual/en/simplexmlelement.addchild.php

... says "... Adds a child element to the node and returns a SimpleXMLElement of the child  ..."
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40444987
Adds a child element to the node and returns a SimpleXMLElement of the child
In this instance we are not working with a node; we are working with the end of a numerically indexed array.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:cescentman
ID: 40445633
Nope you've lost me here. The code on the PHP manual shows:-

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

Open in new window


My code has:-

$keyword = $array->Keywords->Activities->addChild('Activity');

Open in new window


... what I was struggling for was the correct syntax for the next line.
0
 
LVL 1

Author Comment

by:cescentman
ID: 40445637
What am I misunderstanding here?
0
 
LVL 1

Author Comment

by:cescentman
ID: 40445641
@Dzynit it made no difference. Thanks.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40445682
Th PHP sample movie database is not the same thing as the code example you posted with the question.  The PHP samples are set up to illustrate PHP object-oriented programming, and are provided to give us a stable platform for the illustrations.  It's an apples to oranges comparison that we have here.

PHP Objects have nodes, sometimes called properties or branches/twigs/leaves.  PHP Arrays have keys and values.  For better or worse, PHP uses different notation to refer to these different data structures, and each of the data structures can be nested inside the other.  The square bracket notation is used to append a value (and optionally a named key) to the end of an array.  Install this, run it, and look at the output to see the before-and-after for the array.
<?php // demo/temp_cescentman_array.php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28555254.html

// AN ARRAY OF THREE ELEMENTS, BY DEFAULT THESE WILL HAVE NUMERIC KEYS
$arr = array('A', 'B', 'C');
var_dump($arr);

// ADD AN ELEMENT TO THE END OF THE ARRAY
$arr['NEW THING'] = 'NEWLY ADDED ELEMENT';
var_dump($arr);

Open in new window


Next, install this and run it.  Note the changes in the data structure after each step.
<?php // demo/temp_cescentman_object.php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28555254.html

// AN XML STRING
$xml = <<<EOD
<thing>
  <sub_thing>Foo</sub_thing>
</thing>
EOD;

// AN OBJECT CREATED FROM THE XML
$obj = simpleXML_Load_String($xml);
var_dump($obj);

// ADDING A CHILD ELEMENT, INITIALLY AN OBJECT NODE
$obj->addChild('nother_sub_thing');
var_dump($obj);

// SETTING A VALUE ON THE CHILD ELEMENT CHANGES THE DATA TYPE TO STRING
$obj->nother_sub_thing = 'Bar';
var_dump($obj);

Open in new window

0
 
LVL 1

Author Comment

by:cescentman
ID: 40447141
Thanks @Ray Passeur. I now understand what I'm doing.

For anyone referencing this in the future here is an amendment that aligns with the XML data structure I was playing with at the outset:-

<?php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28555254.html

// AN XML STRING
$xml = <<<EOD
<things>
    <thing>
        <sub_thing>Foo</sub_thing>
    </thing>
</things>
EOD;

// AN OBJECT CREATED FROM THE XML
$obj = simpleXML_Load_String($xml);
var_dump($obj);

// ADDING A CHILD ELEMENT, INITIALLY AN OBJECT NODE
$obj->addChild('another_thing');
var_dump($obj);

$obj->thing->addChild('another_sub_thing');
var_dump($obj);

// SETTING A VALUE ON THE CHILD ELEMENT CHANGES THE DATA TYPE TO STRING
$obj->another_thing = 'Bar';
var_dump($obj);

$obj->thing->another_sub_thing = 'Bar';
var_dump($obj);

echo $obj->asXML();

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40447163
Community standards matter, @cescentman.  Please see the Experts-Exchange Grading Guidelines, and then explain why you gave the worst possible grade anyone can give a colleague at E-E.  

Looking forward to your response.  Thanks, ~Ray
0
 
LVL 1

Author Comment

by:cescentman
ID: 40447230
Ray

OK here we go. I have a great deal of respect for the depth of your knowledge (which far outweighs mine) and the detailed, well organised and superbly annotated examples you give. And I am sure that the point accolades you have gathered are well merited. What I have noticed however is that you have a tendency to provide answers to question that aren't being asked.

Your explanation was effective and I understood the answer and it helped me move on. However I think from my first post it was fairly unambiguous that my question was on how to use addchild(). It is my feeling that instead of this you assumed I was misunderstanding the issue and spent time trying to instruct me on something I didn't ask for or need,: how to resolve the matter as an array. The question "Why do you want to use addChild()?  What do you expect it to do for you?" would have saved us both much time had it been asked at the outset; even better if you had just provided the last answer minus the red herring of the first lot of code.

I have no wish to sound ungrateful for the immense help you have given me and others including the impressive array of briefing documents you have written but communities are just that, communities not hierarchies.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40447269
...my question was on how to use addchild()
And you gave an example that clearly showed that addChild() was the wrong tool for the data you showed us in the question.  We cannot add nodes to arrays.  PHP does not work that way.  It's kind of hard to know what you know and what you don't know, or exactly where you're going with a question like this, unless we have some dialog about it.  Unfortunate as it may be, I was at the php[World] conference every day of the week and had only limited time to donate to E-E throughout.

Anyway, the grading guidelines call for an explanation when you give a bad grade, and I still would like to hear your explanation of the "C" grade, in keeping with the E-E grading guidelines published here:
http://support.experts-exchange.com/customer/portal/articles/481419
0
 
LVL 1

Author Comment

by:cescentman
ID: 40447363
What do you think you merit @Ray Paseur?
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now