【问题标题】:How to get attributes from array without attributes functions如何从没有属性函数的数组中获取属性
【发布时间】:2017-12-27 10:17:07
【问题描述】:

我想知道如何在不使用attrubites() 的情况下从数组中读取属性。以下是我的 xml 的一部分:

<?xml version="1.0" encoding="UTF-8"?>
<offer file_format="IOF" version="1.0" generated="2017-12-27 11:04:38" >
<products currency="PLN">
    <product id="2055">
        <price gross="709" net="577"/>
    </product>

下面是我的读取所有属性的代码。我想删除$product-&gt;attributes()-&gt;id,因为它返回一个数组值,我需要用json_decode(json_encode($id), TRUE);“清理”它,然后用$xmlArray[0]; 读取一个值。

$xmlUrl = 'myfile.xml';
$xmlVar = simplexml_load_string(file_get_contents($xmlUrl));
foreach ($xmlVar AS $products) {
    foreach ($products AS $product) {
        $id = $product->attributes()->id;

        $xmlArray = json_decode(json_encode($id), TRUE);
        $withOutId = $xmlArray[0];
    }
}

我想通过移动把这个数组转换成字符串

json_decode(json_encode($id), TRUE);

一开始,但我不知道如何读取属性。感谢您的帮助。

亲切的问候

【问题讨论】:

  • file_get_contents 不返回数组。你可以使用 fopen() 和 fgets() 循环来创建一个数组

标签: php arrays xml


【解决方案1】:

线

$id = $product->attributes()->id;

不返回一个数组,它返回一个SimpleXMLElement 对象。无需通过json_encode/decode 运行,只需将其转换为基本的 PHP 类型即可:

$id = (int) $product->attributes()->id;
var_dump($id); // int(2055)

另一种更简洁的访问属性的方法是使用数组样式的语法:

$id = (int) $product['id'];
var_dump($id); // int(2055)

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 2018-03-16
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多