首页 > 解决方案 > PHP - SimpleXMLElement - 如何访问此元素

问题描述

我正在尝试访问 SimpleXMLElement“数组”中的元素。

我的 XML 如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
    <changeinfo>
      <changes app_ver="01.16">
        <![CDATA[
          Minor interface changes
          
          Please visit http://community.wbgames.com/t5/Mortal-Kombat-X/ct-p/MKX for more details.
        ]]>
      </changes>
      <changes app_ver="01.15">
        <![CDATA[
          WBPlay unlockables no longer requires WBPlay
        ]]>
      </changes>
      <changes app_ver="01.14">
        <![CDATA[
          General Game Play and Balance Tweaks
          
          Please visit http://community.wbgames.com/t5/Mortal-Kombat-X/ct-p/MKX for more details.
        ]]>
      </changes>
    </changeinfo>

加载它simplexml_load_string()会给我以下 var_dump 结果:

object(SimpleXMLElement)#40 (1) {
  ["changes"]=>
  array(16) {
    [0]=>
    object(SimpleXMLElement)#39 (1) {
      ["@attributes"]=>
      array(1) {
        ["app_ver"]=>
        string(5) "01.16"
      }
    }
    [1]=>
    object(SimpleXMLElement)#41 (1) {
      ["@attributes"]=>
      array(1) {
        ["app_ver"]=>
        string(5) "01.15"
      }
    }
    [2]=>
    object(SimpleXMLElement)#42 (1) {
      ["@attributes"]=>
      array(1) {
        ["app_ver"]=>
        string(5) "01.14"
      }
  }
}

如何访问changes我想要其内容的条目?

例如,我该怎么做:

echo $xml->changes['01.16'];

期望它输出第一个条目内容(Minor interface changes ...)?

标签: phpsimplexml

解决方案


尝试类似:

$string = <<<XML
[your xml above]
XML;

$xml = simplexml_load_string($string);
$results = $xml->xpath('.//changes[@app_ver="01.16"]'); 
echo (trim($results[0]));

输出:

Minor interface changes
          
          Please visit http://community.wbgames.com/t5/Mortal-Kombat-X/ct-p/MKX for more details.

推荐阅读