如何从标记名称开头有“@”的xml获取值?

时间:2022-10-27 07:57:34

I'm trying to get values from a XML file, but I have a problem. One of tag name starts with "@". So I'm getting an error on that.

我正在尝试从XML文件中获取值,但我遇到了问题。其中一个标签名称以“@”开头。所以我收到了一个错误。

This is my xml

这是我的xml

object(SimpleXMLElement)#537 (1) { ["urun"]=> array(5225) { [0]=> object(SimpleXMLElement)#547 (1) { ["@attributes"]=> array(7) { ["id"]=> string(4) "2972" ["secenekid"]=> string(1) "4" ["grup"]=> string(4) "YAŞ" ["ozellik"]=> string(1) "1" ["fiyat"]=> string(1) "0" ["agirlik"]=> string(1) "0" ["Stok"]=> string(1) "0" } } [1]=> object(SimpleXMLElement)#548 (1) { ["@attributes"]=> array(7) { ["id"]=> string(4) "2972" ["secenekid"]=> string(1) "5" ["grup"]=> string(4) "YAŞ" ["ozellik"]=> string(1) "2" ["fiyat"]=> string(1) "0" ["agirlik"]=> string(1) "0" ["Stok"]=> string(1) "0" } } 

I'm trying to get like that.

我想要那样做。

$url = "http://xx.com";
$xml = simplexml_load_file($url);

foreach($xml->urun->@attributes as $val) {
echo $val->id; 
}

and this is the error what I see

这就是我所看到的错误

syntax error, unexpected '@', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

so what should I do know for to solve that?

那么我该怎么知道才能解决这个问题呢?

Thanks.

谢谢。

2 个解决方案

#1


0  

The curly braces syntax can be used to access such properties:

花括号语法可用于访问此类属性:

$xml->urun->{'@attributes'}

See PHP curly brace syntax for member variable

请参阅成员变量的PHP大括号语法

In this case you could also use $xml->urun->attributes(), see Accessing @attribute from SimpleXML

在这种情况下,您还可以使用$ xml-> urun-> attributes(),请参阅从SimpleXML访问@attribute

#2


-3  

I find it easiest to convert xml to arrays via JSON encode/decode because array keys can contain '@' with no problem and arrays are easy to traverse:

我发现通过JSON编码/解码将xml转换为数组最容易,因为数组键可以包含“@”而没有问题,并且数组很容易遍历:

$xml = simplexml_load_file($url);
$json = json_encode($xml);
$data = json_decode($json,true);

Now you have an array. Use print_r to see its shape on screen. To access attributes you would do:

现在你有一个数组。使用print_r在屏幕上查看其形状。要访问您要执行的属性:

echo $data['@attributes']['Name']

#1


0  

The curly braces syntax can be used to access such properties:

花括号语法可用于访问此类属性:

$xml->urun->{'@attributes'}

See PHP curly brace syntax for member variable

请参阅成员变量的PHP大括号语法

In this case you could also use $xml->urun->attributes(), see Accessing @attribute from SimpleXML

在这种情况下,您还可以使用$ xml-> urun-> attributes(),请参阅从SimpleXML访问@attribute

#2


-3  

I find it easiest to convert xml to arrays via JSON encode/decode because array keys can contain '@' with no problem and arrays are easy to traverse:

我发现通过JSON编码/解码将xml转换为数组最容易,因为数组键可以包含“@”而没有问题,并且数组很容易遍历:

$xml = simplexml_load_file($url);
$json = json_encode($xml);
$data = json_decode($json,true);

Now you have an array. Use print_r to see its shape on screen. To access attributes you would do:

现在你有一个数组。使用print_r在屏幕上查看其形状。要访问您要执行的属性:

echo $data['@attributes']['Name']