简体   繁体   中英

xml attributes name error?

im trying to parse a simple xml string which contain basic attributes

<hash>
<engine-type>
I4 DI
</engine-type>
<body-style>
SAV 4D
</body-style>
<year>
2012
</year>
</hash>

the problem happened when i tried to print out those 2 attributes engine-type and body-style the xdebug gives error

$result = simplexml_load_string($query);
$enginetype = $result->engine-type;
$bodystyle = $result->body-style ;
echo $enginetype .'<br />'. $bodystyle ;

those are the errors came from xdebug

Notice: Use of undefined constant type - assumed 'type'
Notice: Use of undefined constant style - assumed 'style

when i tried to save them to my database the value 0
other attributes just work fine

Use curly complex syntax to represent identifiers with special characters.

$enginetype = $result->{'engine-type'};
$bodystyle = $result->{'body-style'} ;

engine-type is not a valid label name in PHP, so cannot be used directly to refer to a property of an object.

PHP allows "variable properties", using the curly-brace syntax, which accept a property name as the result of some expression: that expression can be as simple as a string.

$result->{'engine-type'};

This allows one to construct property names dynamically (which is not needed in this case) like

$var = 'bar';
$result->{'foo-'.$var};

We have an example of this syntax, dealing with exactly the same sort of scenario as in the question, currently available as Example #3 on the SimpleXML Basic Usage manual page.

Example #3 Getting <line>

 <?php include 'example.php'; $movies = new SimpleXMLElement($xmlstr); echo $movies->movie->{'great-lines'}->line; ?> 

The above example will output:

PHP solves all my web problems

The problem is that your expression is being interpreted as variable $result->engine minus constant type . Try this insted:

var_dump($result->{'engine-type'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM