Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP simple XML to array - minus character problem [duplicate]

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?

like image 483
Jens Törnell Avatar asked Aug 27 '26 22:08

Jens Törnell


1 Answers

The solution is to use the following:

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

and so on for all attributes with hyphens.

like image 154
Mike Lewis Avatar answered Aug 30 '26 12:08

Mike Lewis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!