如何获取标签的值<category>并将其写入数组?
问题是我无法以任何方式获取标签<category>(家用灯echo)的内容,除了返回对象(SimpleXMLElement)之外的任何尝试。
<?php
$file = <<<XML
<yml_catalog date="2019-10-18 16:00">
<shop>
<categories>
<category id="41" parentId="38">Лампы бытовые</category>
<category id="42" parentId="41">A60</category>
</categories>
</shop>
</yml_catalog>
XML;
$value = new SimpleXMLElement($file);
$categories = [];
foreach ($value->shop->categories->category as $c) {
$categories[(int)$c->attributes()['id']] =
[
'id' => (int)$c->attributes()['id'],
'parentId' => (int)$c->attributes()['parentId'],
'name' => $c[0] // object(SimpleXMLElement)
];
echo '<pre>';
var_dump($categories[(int)$c->attributes()['id']]);
echo '</pre>';
echo '<hr>';
}
导致var_dump循环
array(3) {
["id"]=>
int(41)
["parentId"]=>
int(38)
["name"]=>
object(SimpleXMLElement)#6 (2) {
["@attributes"]=>
array(2) {
["id"]=>
string(2) "41"
["parentId"]=>
string(2) "38"
}
[0]=>
string(25) "Лампы бытовые"
}
}
要获取对象的字符串值,
SimpleXMLElement您需要将此对象转换为类型string(这实际上是在调用时隐式echo完成的,但您需要显式执行):我认为你可以这样做:
这个问题并不完全清楚。标签内的内容?
https://www.php.net/manual/ru/simplexmlelement.tostring.php