-2

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.

2 Answers2

0

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

Community
  • 1
  • 1
Shira
  • 6,392
  • 2
  • 25
  • 27
-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:

$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']
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • Doing all this encoding and decoding just to get a slightly different access syntax seems like an overkill to me. – Shira Aug 09 '16 at 15:53
  • @ShiraNai7 actually I agree with you :-) It would be overkill if it were just for that purpose. I gave my reasons including `arrays are easy to traverse`. I just didn't elaborate so since you probably downvoted, let me elaborate a bit: By doing it this way, I can perform arithmetic functions on the data, I can `array_map`, `array_filter`, `array_merge`... I can add it to other arrays, I can do `array_intersect` to quickly compare to other xml data... PHP is just a beast with arrays so... – BeetleJuice Aug 09 '16 at 15:57
  • It might be useful if a complete conversion to a multidimensional array is needed but it still feels dirty :) – Shira Aug 09 '16 at 18:13
  • Bad Idea, SimpleXML implements many interfaces like ArrayAccess, Traversable and Magic Methods. You will actually loose both information and ease of access. Check `SimpleXMLElement::xpath()` for example. – ThW Aug 10 '16 at 09:26