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.
This is my 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.
The curly braces syntax can be used to access such properties:
$xml->urun->{'@attributes'}
See PHP curly brace syntax for member variable
In this case you could also use $xml->urun->attributes()
, see Accessing @attribute from SimpleXML
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:
$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:
echo $data['@attributes']['Name']