开发者

How can I reference elements with names like 'element-name' using SimpleXml

开发者 https://www.devze.com 2022-12-08 03:20 出处:网络
How can I parse an XML document like this: <feed> <item> <element-name>Element value</element-name>

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;
$i开发者_开发问答tem->elementname;
$item->elementName;

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


You could use something like this:

$name = "element-name";
$item->{$name};


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消