Search code examples
phpsimplexml

SimpleXML Export "SimpleXMLElement::__set_state(array(" in Variable


I'm trying to take a variable from an xml file and save it as a php file

     $xmlresponse = simplexml_load_string($dom->saveXML());
   $shipmentid = $xmlresponse->ListInboundShipmentsResult->ShipmentData->member->ShipmentId;
 echo '<br />' . $shipmentid . '<br />';


 $todaydt = new DateTime('today');
 $today3 = $todaydt->format('m-d-Y') . PHP_EOL;
 $today = rtrim($today3);
$var_str = var_export($shipmentid, true);
$var = "<?php\n\n\$shipmentid = $var_str;\n\n?>";
file_put_contents('shipmentid_' . $today . '.php', $var);

 }

But in my shipmentid_11-11-2016.php file it is giving me

$shipmentid = SimpleXMLElement::__set_state(array( 0 => 'shipmentid', ));

How can I save the variable so it is just simply

$shipmentid = 'shipmentid';

?


Solution

  • When you do

    echo '<br />' . $shipmentid . '<br />';
    

    php implicitly converts $shipmentid value to a string. var_export does not do it, so you need to convert it by yourself:

    $var_str = strval($shipmentid);
    

    Next thing is that $var_str is a string and does not contains any quotes around. So, again you need to write quotes by yourself:

    // with double quotes
    $var = "<?php\n\n\$shipmentid = \"$var_str\";\n\n?>";
    // with single quotes
    $var = "<?php\n\n\$shipmentid = '$var_str';\n\n?>";