views:

42

answers:

1

I'm getting the following error when trying to add some data from myXml.xml to a string: Parse error: syntax error, unexpected T_OBJECT_OPERATOR.

    $xmlstr = file_get_contents('myXml.xml');
    $xml = new SimpleXMLElement($xmlstr); 

    foreach($xml->order as $order){
            $replace = array();
            $firstName = (string) $order->billing-address->first-name;
            $lastName = (string) $order->billing-address->last-name;
    }

I can't provide my XML directly as it contains sensitive data.

Thanks, Sam

+8  A: 

The - sign means subtraction. To use it in property names, you must use this syntax:

$firstName = (string) $order->{"billing-address"}->{"first-name"};
$lastName = (string) $order->{"billing-address"}->{"last-name"};

In general, it's probably better to use firstName, billingAddress, etc. as property names to avoid this. See CamelCase. In this case, however, you may have no control over the the XML input.

Artefacto
@Sam The way your code is now, PHP understands: `$order->billing - address->first - name;` address and name are considered constants for this purpose. But you do not have those constants defined, so PHP thinks you mean the string "address" and "name" and trying to use the [T_OBJECT_OPERATOR](http://php.net/manual/en/tokens.php), e.g. `->` on a String doesnt work.
Gordon
Brilliant, thank you both for our answers. You're right about not having control over the XML. I'll give it a go now. Edit: Worked perfectly, thanks!
Sam