【问题标题】:PHP Parse XML with AttributesPHP 使用属性解析 XML
【发布时间】:2012-04-01 08:57:29
【问题描述】:

我有一个 XML 文档,我正在尝试获取一些值,但不知道如何获取属性。结构和值的示例如下:

<vin_number value="3N1AB51D84L729887">

  <common_data>

    <engines>

    </engines>

  </common_data>

  <available_vehicle_styles>

    <vehicle_style name="SE-R 4dr Sedan" style_id="100285116" complete="Y">

      <engines>

        <engine brand="" name="ED 2L NA I 4 double overhead cam (DOHC) 16V"></engine>

      </engines>

    </vehicle_style>

  </available_vehicle_styles>

</vin_number>

我正在尝试获取 engine["name"] 属性(不是 "ENGINES")。我认为以下方法可行,但出现错误(我无法解析过去的“vehicle_style”)

$xml = simplexml_load_file($fileVIN);

foreach($xml->vin_number->available_vehicle_styles->vehicle_style->engines->engine->attributes() as $a => $b) {
    echo $b;
}

【问题讨论】:

  • 你一直说你“得到错误”,知道这些错误的内容会很有帮助。

标签: php xml


【解决方案1】:

假设您的 XML 结构与 this example XML 相同,则以下两个 sn-ps 将获取引擎名称。

属性层级方式(分成多行以便您阅读)。

$name = (string) $xml->vin_number
                     ->available_vehicle_styles
                     ->vehicle_style
                     ->engines
                     ->engine['name'];

或者更简洁的 XPath 方式。

$engines = $xml->xpath('//engines/engine');
$name = (string) $engines[0]['name'];

除非您的 XML 中有多个引擎名称,否则根本不需要使用 foreach 循环。

(See both snippets running on a codepad.)

【讨论】:

    【解决方案2】:

    使用SimpleXMLElement::attributes方法获取属性:

    foreach($xml->available_vehicle_styles->vehicle_style as $b) {
        $attrs = $b->attributes();
        echo "Name = $attrs->name";
    }
    

    注意:我略微更改了从 $xml 开始的元素的“路径”,因为它是为我加载片段的方式。

    【讨论】:

    • 我明白了,但我需要做的是获取“引擎”的属性名称,所以我想我会像上面一样做,但我不断收到错误:$xml->available_vehicle_styles- >vehicle_style->engines->engine as $b
    【解决方案3】:

    通过这种布局,每个引擎块可能有多个引擎,因此您必须明确选择第一个。 (假设你确定只有一个。)

    $name = $xml->available_vehicle_styles->vehicle_style->engines->engine[0]->attributes()->name;
    

    【讨论】:

    • 我在上面尝试了您的代码并得到了错误...如果我执行以下操作,它会打印出来很好... ($xml->vin_number->available_vehicle_styles->vehicle_style[0]->attributes( )->name) 所以对于引擎我尝试了以下但仍然有错误... ($xml->vin_number->available_vehicle_styles->vehicle_style[0]->engines[0]->engine[0]->attributes( )->名称)
    • 我一整天都在做这件事,我刚刚给我下载 XML 文件的公司发了电子邮件。我编辑了上面 XML 数据的结构。我不知道他们发送给我的文件中是否有错误,但我正在尝试访问第二个引擎->引擎节点。当第一个为空时,我得到一个错误。是不是我做错了什么?
    • 顶部添加了一个名为“common_data”的节点
    • 它与您最初发布的 XML 完全兼容:codepad.org/r2Je30qJ
    • 我的帖子上面有几个答案。我认为正在下载的 XML 文件中存在工件。
    猜你喜欢
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多