gpt4 book ai didi

php - SimpleXML 和 PHP : Extract part of XML document & convert as Array

转载 作者:行者123 更新时间:2023-12-02 08:39:30 25 4
gpt4 key购买 nike

考虑以下 XML:

<?xml version="1.0" encoding="UTF-8"?>
<OS>
<data>
<OSes>
<centos>
<v_5>
<i386>
<id>centos5-32</id>
<name>CentOS 5 - 32 bit</name>
<version>5</version>
<architecture>32</architecture>
<os>centos</os>
</i386>
<x86_64>
<id>centos5-64</id>
<name>CentOS 5 - 64 bit</name>
<version>5</version>
<architecture>64</architecture>
<os>centos</os>
</x86_64>
</v_5>
<v_6>
<i386>
<id>centos6-32</id>
<name>CentOS 6 - 32 bit</name>
<version>6</version>
<architecture>32</architecture>
<os>centos</os>
</i386>
<x86_64>
<id>centos6-64</id>
<name>CentOS 6 - 64 bit</name>
<version>6</version>
<architecture>64</architecture>
<os>centos</os>
</x86_64>
</v_6>
</centos>
<ubuntu>
<v_10>
<i386>
<id>ubuntu10-32</id>
<name>Ubuntu 10 - 32 bit</name>
<version>10</version>
<architecture>32</architecture>
<os>ubuntu</os>
</i386>
<amd64>
<id>ubuntu10-64</id>
<name>Ubuntu 10 - 64 bit</name>
<version>10</version>
<architecture>64</architecture>
<os>ubuntu</os>
</amd64>
</v_10>
</ubuntu>
</OSes>
</data>
</OS>

从上面的XML文档中,我想提取以下5个元素节点

  1. <id>
  2. <name>
  3. <version>
  4. <architecture>
  5. <os>

并将它们作为数组。我尝试执行以下操作:

<?php 
require_once "xml.php";

try {
$xml = new SimpleXMLElement($xmlstr);
foreach($xml->xpath(' //id | //name | //version// | //architecture | //os ') as $record) {
echo $record;
}
} catch(Exception $e){
echo $e->getMessage();
}

上面的代码可以工作,但每个记录都是一个单独的对象。我希望有人将所有 5 个元素节点合并为一个数组元素。像这样的东西:

$osList = Array( [0] => Array(
["id"] => "<id>",
["name"] => "<name>",
["version"] => "<version>",
....
)
.....
);

语法不正确,但你明白了。知道如何做到这一点吗?

最佳答案

这可能有帮助

$obj = new SimpleXMLElement($xml);
$rtn = array();
$cnt = 0;
foreach($obj->xpath('///OSes/*/*') as $rec)
{
foreach ($rec as $rec_obj)
{
if (!isset($rtn[$cnt]))
{
$rtn[$cnt] = array();
}

foreach ($rec_obj as $name=>$val)
{
$rtn[$cnt][(string)$name] = (string)$val;
}
++$cnt;
}
}

关于php - SimpleXML 和 PHP : Extract part of XML document & convert as Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7015084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com