1

I am retrieving an XML data from url and I want to extract data from the particular nodes.

Here is my XML Data

<person>
  <first-name>ABC</first-name>
  <last-name>XYZ</last-name>
</person>

Here's my PHP code:

$content = file_get_contents($url);

$xml = simplexml_load_string($content);

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child->first-name . "<br>";
  }

PHP returns this error:

Use of undefined constant name - assumed 'name'

So where am I going wrong?

hakre
  • 193,403
  • 52
  • 435
  • 836
user1889200
  • 63
  • 1
  • 1
  • 7
  • Also please see the [Basic Usage of SimpleXML, especially *Example #3 Getting * in the PHP Manual](http://php.net/simplexml.examples-basic) – hakre Apr 07 '13 at 15:16

3 Answers3

0

Try to use this :

<person>
  <firstname>ABC</firstname>
  <lastname>XYZ</lastname>
</person>

and then :

$content = file_get_contents($url);

$xml = simplexml_load_string($content);

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child->firstname . "<br>";
  }

Does it works ?

Edit : you won't have any datas in $xml->children() cause you don't have any. Try to do something like this :

<person>
  <firstname>ABC</firstname>
  <lastname>XYZ</lastname>
  <other>
    <first>111</first>
    <second>222</second>
  </other>
</person>

<?php 
$content = file_get_contents("test.xml");

$xml = simplexml_load_string($content);

foreach($xml->children() as $child)
{   
    echo $child->getName() . ": " .$child->first . "<br>";
}

 ?>

this will echo this :

firstname: 
lastname: 
other: 111

I you want to have the first node, you can simply do :

echo $xml->firstname
Kai23
  • 1,556
  • 2
  • 16
  • 30
  • No. It doesnot. The $child->getName returns the node name only. But $child->firstname Or $child->first-name doesnot return the node's data – user1889200 Apr 07 '13 at 15:07
0

The '-' isn't allowed in a variable name. $child->first-name is interpreted as $child->first minus name. You should find another way to get the content.

Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Janoz
  • 953
  • 4
  • 9
0

As already mentioned, you cannot use - in the variable name. From what I can gather though, you are simply trying to print out the tag name and value. If so, you're probably after this:

foreach($xml->children() as $child)
{
    echo "{$child->getName()}: $child <br />";
}
juco
  • 6,331
  • 3
  • 25
  • 42