0

How can I parse an XML document like this:

<feed>
  <item>
    <element-name>Element value</element-name>
  </item>
</feed>

If I try the following, it doesn't work:

$xmlObject = simplexml_load_string($xmlString);

foreach($xmlObject->item as $item) {
    $elementName= $item->element-name; // Obviously doesn't work.
}

I've tried:

$item->element_name;
$item->elementname;
$item->elementName;

None work. How do I access this element's value?

2 Answers 2

1

You could use something like this:

$name = "element-name";
$item->{$name};
Sign up to request clarification or add additional context in comments.

Comments

0

simplexml_load_string does not like it when you try and pass it element nodes with dashes/hyphens (-).

You have two options here.

Encapsulate the element name with curly braces ({}):

$elementName = $item->{'element-name'};

Or turn it into a variable you can replace out:

$elementNameNode = 'element-name';
$elementName = $item->$elementNameNode;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.