3

I have a XML file with data and run the following code:

<?php
$xml = simplexml_load_file("index.xml");
$result = $xml->xpath("product");

echo $result[0]->name . '<br />';
echo $result[0]->price . '<br />';
echo $result[0]->info-url . '<br />';
echo $result[0]->image-url . '<br />';
echo $result[0]->longdescription . '<br />';
?>

Part of my XML file

<product>
  <name>Test</name>
  <price>100</price>
  <info-url>http://www.test.com</info-url>
  <image-url>http://www.test.com/image.jpg</image-url>
</product>

I get this error:

"Notice: Use of undefined constant url - assumed 'url' in C:\wamp\www\concepts\xml-to-array\index.php on line 11"

It does not like the minus character. How do I get it?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

3 Answers3

8

The solution is to use the following:

$result[0]->{'image-url'}

and so on for all attributes with hyphens.

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
-1

Instead of xpath, I like using:

$url = "filename.xml";
$simple = simplexml_load_file($url);
$arr = json_decode( json_encode($simple) , 1);

I can then access elements by:

echo $arr['product']['image-url'];

According to comment, this is wasteful, however I would prefer to sacrifice a few kilobytes of memory / and a few microseconds in processing time for a cleaner means of navigation and significantly improved code readability. Especially when it comes to deeply nested xml files.

Gravy
  • 12,264
  • 26
  • 124
  • 193
  • Encoding & decoding is waste of memory. SimpleXML library provides sufficient access to data (@Mike Lewis answer) – Minimihi Oct 07 '15 at 10:42
  • @Minimihi - Library provides sufficient access to the data, but the format in which it is returned is not intuitive. As such, I would prefer to sacrifice a few kilobytes of memory / and a few microseconds in processing time for a cleaner means of navigation and code readability. – Gravy Oct 07 '15 at 11:19
-1
$arr = json_decode( json_encode($simple) , 1);

looks simple but generates bad array, ex.

<product>
  <name>Test</name>
  <price/>
</product>

returns "price" as empty subarray

[price] => Array
    (
    )
adq82
  • 29
  • 1