Search code examples
phpxmlsimplexmlspecial-characters

PHP simple XML to array - minus character problem


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?


Solution

  • The solution is to use the following:

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

    and so on for all attributes with hyphens.