我正在尝试从pre - shop API中获取XML中的一些数据确切地说,我想创建一个数组,它将作为关键id(例如2)和值的名称->语言。我使用simplexml_load_string将xml转换为数组
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<category>
<id>
<![CDATA[2]]>
</id>
...
<name>
<language id="1" xlink:href="https://mosty.com/api/languages/1">
<![CDATA[Home]]>
</language>
</name>
<link_rewrite>
<language id="1" xlink:href="https://mosty.com/api/languages/1">
<![CDATA[home]]>
</language>
</link_rewrite>
...
</category>
</prestashop>
请看下面的代码。我想你有多个<category>
元素:
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<category>
<id>
<![CDATA[2]]>
</id>
<name>
<language id="1" xlink:href="https://mosty.com/api/languages/1">
<![CDATA[Home]]>
</language>
</name>
<link_rewrite>
<language id="1" xlink:href="https://mosty.com/api/languages/1">
<![CDATA[home]]>
</language>
</link_rewrite>
</category>
</prestashop>';
$obj = simplexml_load_string($xml);
$result = [];
foreach($obj->category as $item) {
$result[trim($item->id)] = trim($item->name->language);
}
var_dump($result);
输出array(1) { [2]=> string(4) "Home" }
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<category>
<id>
<![CDATA[2]]>
</id>
<name>
<language id="1" xlink:href="https://mosty.com/api/languages/1">
<![CDATA[Home]]>
</language>
</name>
<link_rewrite>
<language id="1" xlink:href="https://mosty.com/api/languages/1">
<![CDATA[home]]>
</language>
</link_rewrite>
</category>
</prestashop>';
$obj = simplexml_load_string($xml);
$result = [];
foreach($obj->category as $item) {
$result[trim($item->id)] = trim($item->name->language);
}
var_dump($result);
array(1) { [2]=> string(4) "Home" }