I'm trying to use simplexml_load_string to get the Status and Text values from the following XML response;
<?xml version="1.0" encoding="utf-16"?>
<cXML payloadID="online" xml:lang="en" timestamp="2017-12-04T15:57:47.6693296+00:00">
<Response>
<Status code="402" text="
product 325552not in customer[20690] pricelist" />
</Response>
</cXML>
In my PHP code I am getting the XML above from $reply:
$reply = curl_exec($curl);
I am then using simplexml_load_string like so:
$responseData = simplexml_load_string($reply);
echo 'Sync Order - '. $order->getIncrementId() . ' Status '. $responseData->Response->Status['code'] .' - '. $responseData->Response->Status['text'];
But this doesn't seem to get the code and text from the XML response above. Wondering if anyone has any ideas to help?
Thank you.
Note: The cXML is correct.
I've tried it with the added xml header and UTF-16 encoding bit and it fails to load with an error...
PHP Warning: simplexml_load_string(): Entity: line 1: parser error :
Document labelled UTF-16 but has UTF-8 content in
A simple but crude way round it is to change the UTF in the xml element to UTF8...
$reply = preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $reply);
$responseData = simplexml_load_string($reply);
This then gives the output as expected...
Status 402 -
product 325552not in customer[20690] pricelist
Related
I'm trying to parse OTA service's XML response in PHP. I have tried below code but no luck.
$doc = new DOMDocument();
$doc->loadXML($response);
$XMLresults = $doc->getElementsByTagName("OTA_VehAvailRateRS");
I want to get different tags value from xml response. Can someone help me out from this? Thanks. For example i want to parse following xml response:
<?xml version="1.0"?>
<OTA_VehAvailRateRS xmlns="http://www.opentravel.org/OTA/2003/05" TimeStamp="2018-02-28T01:12:27" Target="Test" Version="4.500" SequenceNmbr="1">
<Success/>
<VehAvailRSCore>
<VehRentalCore PickUpDateTime="2018-03-13T08:00:00" ReturnDateTime="2018-03-30T08:00:00">
<PickUpLocation LocationCode="TEST"/>
<ReturnLocation LocationCode="TEST"/>
</VehRentalCore>
<VehVendorAvails>
<VehVendorAvail>
<VehAvails> <VehAvail>
<VehAvailCore Status="Available">
<Vehicle Code="TEST15" VendorCarType="TEST15" Description="TEST"/>
<RentalRate>
<RateDistance Unlimited="True" DistUnitName="Mile" VehiclePeriodUnitName="RentalPeriod"/>
<VehicleCharges>
<VehicleCharge Description="TEST" Amount="1299.35" CurrencyCode="" GuaranteedInd="True" Purpose="1"> <Calculation UnitCharge="33.32" UnitName="Hour"/>
<Calculation UnitCharge="1560.00" UnitName="Month"/>
<Calculation UnitCharge="499.75" UnitName="Week"/>
<Calculation UnitCharge="99.95" UnitName="Day"/>
<TaxAmounts> </TaxAmounts>
</VehicleCharge>
</VehicleCharges>
</RentalRate>
<Fees> </Fees>
<TotalCharge CurrencyCode="" RateTotalAmount="1299.35" EstimatedTotalAmount="1299.35"/>
<PricedEquips> </PricedEquips> </VehAvailCore> <VehAvailInfo> <PricedCoverages> </PricedCoverages> </VehAvailInfo> </VehAvail> </VehAvails> </VehVendorAvail> </VehVendorAvails> </VehAvailRSCore> </OTA_VehAvailRateRS>
I have found solution. I have used simplexml_load_string() function for parse response. For ex:
$xml = simplexml_load_string($finalresponse);
var_dump($xml); //getting parsed response here
For getting value of different xml nodes i have used below code:
$nodevalue = $xml->VehAvailRSCore->VehRentalCore->attributes()->PickUpDateTime; //this code gives me "2018-03-13T08:00:00" as result
I am doing a curl request and getting the following back:
//....curl stuff....//
$result = curl_exec($curl);
curl_close ($curl);
print_R($result);
<html><body onload="if (parent.submitterLoaded)
parent.submitterLoaded();">{"AuthenticationType":0,
"DateDisplayFormat":1, "SystemURL":"https://rmm.server.com",
"Username”:”user”, "UserID":"12205_1", "Error":"", "Success":true,
"ClientID":1, "SessionGuid":"9eb91231b04-feca-4704-b445-
cc5b369581e3", "tag":"", "LastRequestDateTime":"636421428277379996"}
</body></html><?xml version="1.0" encoding="utf-8"?><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
<LoginResponse xmlns="http://Iris.net" /></soap:Body></soap:Envelope>
I have tried xml_parser_create and
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
and i get a garbled mess in return.
Warning: simplexml_load_string(): Entity: line 1: parser error : XML
declaration allowed only at the start of the document in
/var/www/cron/billing/test.php on line 68
PHP Warning: simplexml_load_string(): b6-bd4dd8a0760b",
"LastRequestDateTime":"636421426011959977"}</body></html><?xml in
/var/www/cron/billing/test.php on line 68
PHP Warning: simplexml_load_string():
^ in /var/www/cron/billing/test.php on line 68
I can see what appears to be some json at the {"Keys" area of the response. How can i parse this correctly?
What other info do you need to help answer question?
The first warning indicate the parser doesn't like the second part <?xml version... So get rid of it:
$result = substr($result, 0, strpos($result, '<?xml version'));
Then to pull out the JSON string, use:
$jsonString = (string) simplexml_load_string($result)->body;
$array = json_decode($jsonString);
extract the json with DOMDocument, and parse it with json_decode
$domd=#DOMDocument::loadHTML($response);
$json_data=json_decode(trim($domd->getElementsByTagName("body")->item(0)->textContent));
now the stuff in the json can be accessed like $UserID=$json_data->UserID;, ... and the stuff in the HTML can be accessed in $domd, like $loginResponse=$domd->getElementsByTagName("LoginResponse")->item(0)->textContent; - didn't see anything useful in the html other than the json, though..
I’m setting up a PHP site which will gather information from a Dell iDRAC. I want to use the returned information to create a PHP object. The information returned from the first part of the script looks like this.
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="http://www.w3.org/2003/05/soap-envelope" xmlnwsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlnwsen="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlnn1="http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_SystemView" xmlnxsi="http://www.w3.org/2001/XMLSchema-instance">
<Header>
<To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</To>
<Action>http://schemas.xmlsoap.org/ws/2004/09/enumeration/PullResponse</Action>
<RelatesTo>uuid:e5ef952f-fb48-1b48-8003-06c7395d1500</RelatesTo>
<MessageID>uuid:36a3a786-fb4c-1b4c-8012-fc140555dbe0</MessageID>
</Header>
<Body>
<PullResponse>
<Items>
<DCIM_SystemView>
<AssetTag/>
<BIOSReleaseDate>01/20/2014</BIOSReleaseDate>
<BIOSVersionString>2.1.2</BIOSVersionString>
<BaseBoardChassisSlot>NA</BaseBoardChassisSlot>
<BatteryRollupStatus>1</BatteryRollupStatus>
<BladeGeometry>255</BladeGeometry>
<BoardPartNumber>03015MA01</BoardPartNumber>
<BoardSerialNumber>CN7475128I0205</BoardSerialNumber>
<CPLDVersion>1.0.0</CPLDVersion>
<CPURollupStatus>1</CPURollupStatus>
<ChassisModel/>
<ChassisName>Main System Chassis</ChassisName>
<ChassisServiceTag>5P5KMW1</ChassisServiceTag>
<ChassisSystemHeight>5</ChassisSystemHeight>
<DeviceDescription>System</DeviceDescription>
<ExpressServiceCode>12404926945</ExpressServiceCode>
<FQDD>System.Embedded.1</FQDD>
<FanRollupStatus>1</FanRollupStatus>
<HostName/>
<InstanceID>System.Embedded.1</InstanceID>
<LastSystemInventoryTime>20140608040932.000000+000</LastSystemInventoryTime>
<LastUpdateTime>20140522204842.000000+000</LastUpdateTime>
<LicensingRollupStatus>1</LicensingRollupStatus>
<LifecycleControllerVersion>2.1.0</LifecycleControllerVersion>
<Manufacturer>Dell Inc.</Manufacturer>
<MaxCPUSockets>2</MaxCPUSockets>
<MaxDIMMSlots>12</MaxDIMMSlots>
<MaxPCIeSlots>6</MaxPCIeSlots>
<MemoryOperationMode>OptimizerMode</MemoryOperationMode>
<Model>PowerEdge T420</Model>
<NodeID>5P5KMW1</NodeID>
<PSRollupStatus>1</PSRollupStatus>
<PlatformGUID>31574d4f-c0b5-4b80-3510-00504c4c4544</PlatformGUID>
<PopulatedCPUSockets>2</PopulatedCPUSockets>
<PopulatedDIMMSlots>4</PopulatedDIMMSlots>
<PopulatedPCIeSlots>1</PopulatedPCIeSlots>
<PowerCap>317</PowerCap>
<PowerCapEnabledState>3</PowerCapEnabledState>
<PowerState>2</PowerState>
<PrimaryStatus>1</PrimaryStatus>
<RollupStatus>1</RollupStatus>
<ServiceTag>5P5KMW1</ServiceTag>
<StorageRollupStatus>1</StorageRollupStatus>
<SysMemErrorMethodology>6</SysMemErrorMethodology>
<SysMemFailOverState>NotInUse</SysMemFailOverState>
<SysMemLocation>3</SysMemLocation>
<SysMemMaxCapacitySize>393216</SysMemMaxCapacitySize>
<SysMemPrimaryStatus>1</SysMemPrimaryStatus>
<SysMemTotalSize>16384</SysMemTotalSize>
<SystemGeneration>12G Monolithic</SystemGeneration>
<SystemID>1273</SystemID>
<SystemRevision>0</SystemRevision>
<TempRollupStatus>1</TempRollupStatus>
<UUID>4c4c4544-0050-3510-804b-b5c04f4d5731</UUID>
<VoltRollupStatus>1</VoltRollupStatus>
<smbiosGUID>44454c4c-5000-1035-804b-b5c04f4d5731</smbiosGUID>
</DCIM_SystemView>
</Items>
<EndOfSequence/>
</PullResponse>
</Body>
</Envelope>
When I try to use the simplexml_load_string function, it returns the following errors and does not process the data as a string.
PHP Warning: simplexml_load_string(): Entity: line 1: parser error : XML declaration allowed only at the start of the document in php shell code on line 1
PHP Warning: simplexml_load_string(): in php shell code on line 1
PHP Warning: simplexml_load_string(): ^ in php shell code on line 1
However, if I use the EXACT same XML and manually create the variable like this :
<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="http://www.w3.org/2003/05/soap-envelope" xmlnwsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlnwsen="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlnn1="http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_SystemView" xmlnxsi="http://www.w3.org/2001/XMLSchema-instance">
<Header>
<To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</To>
<Action>http://schemas.xmlsoap.org/ws/2004/09/enumeration/PullResponse</Action>
<RelatesTo>uuid:641403a8-fb4a-1b4a-8003-06c7395d1500</RelatesTo>
<MessageID>uuid:b4caac95-fb4d-1b4d-8051-fc140555dbe0</MessageID>
</Header>
<Body>
<PullResponse>
<Items>
<DCIM_SystemView>
<AssetTag/>
<BIOSReleaseDate>01/20/2014</BIOSReleaseDate>
<BIOSVersionString>2.1.2</BIOSVersionString>
<BaseBoardChassisSlot>NA</BaseBoardChassisSlot>
<BatteryRollupStatus>1</BatteryRollupStatus>
<BladeGeometry>255</BladeGeometry>
<BoardPartNumber>03015MA01</BoardPartNumber>
<BoardSerialNumber>CN7475128I0205</BoardSerialNumber>
<CPLDVersion>1.0.0</CPLDVersion>
<CPURollupStatus>1</CPURollupStatus>
<ChassisModel/>
<ChassisName>Main System Chassis</ChassisName>
<ChassisServiceTag>5P5KMW1</ChassisServiceTag>
<ChassisSystemHeight>5</ChassisSystemHeight>
<DeviceDescription>System</DeviceDescription>
<ExpressServiceCode>12404926945</ExpressServiceCode>
<FQDD>System.Embedded.1</FQDD>
<FanRollupStatus>1</FanRollupStatus>
<HostName/>
<InstanceID>System.Embedded.1</InstanceID>
<LastSystemInventoryTime>20140608040932.000000+000</LastSystemInventoryTime>
<LastUpdateTime>20140522204842.000000+000</LastUpdateTime>
<LicensingRollupStatus>1</LicensingRollupStatus>
<LifecycleControllerVersion>2.1.0</LifecycleControllerVersion>
<Manufacturer>Dell Inc.</Manufacturer>
<MaxCPUSockets>2</MaxCPUSockets>
<MaxDIMMSlots>12</MaxDIMMSlots>
<MaxPCIeSlots>6</MaxPCIeSlots>
<MemoryOperationMode>OptimizerMode</MemoryOperationMode>
<Model>PowerEdge T420</Model>
<NodeID>5P5KMW1</NodeID>
<PSRollupStatus>1</PSRollupStatus>
<PlatformGUID>31574d4f-c0b5-4b80-3510-00504c4c4544</PlatformGUID>
<PopulatedCPUSockets>2</PopulatedCPUSockets>
<PopulatedDIMMSlots>4</PopulatedDIMMSlots>
<PopulatedPCIeSlots>1</PopulatedPCIeSlots>
<PowerCap>317</PowerCap>
<PowerCapEnabledState>3</PowerCapEnabledState>
<PowerState>2</PowerState>
<PrimaryStatus>1</PrimaryStatus>
<RollupStatus>1</RollupStatus>
<ServiceTag>5P5KMW1</ServiceTag>
<StorageRollupStatus>1</StorageRollupStatus>
<SysMemErrorMethodology>6</SysMemErrorMethodology>
<SysMemFailOverState>NotInUse</SysMemFailOverState>
<SysMemLocation>3</SysMemLocation>
<SysMemMaxCapacitySize>393216</SysMemMaxCapacitySize>
<SysMemPrimaryStatus>1</SysMemPrimaryStatus>
<SysMemTotalSize>16384</SysMemTotalSize>
<SystemGeneration>12G Monolithic</SystemGeneration>
<SystemID>1273</SystemID>
<SystemRevision>0</SystemRevision>
<TempRollupStatus>1</TempRollupStatus>
<UUID>4c4c4544-0050-3510-804b-b5c04f4d5731</UUID>
<VoltRollupStatus>1</VoltRollupStatus>
<smbiosGUID>44454c4c-5000-1035-804b-b5c04f4d5731</smbiosGUID>
</DCIM_SystemView>
</Items>
<EndOfSequence/>
</PullResponse>
</Body>
</Envelope>
XML;
It works like a charm. So, my question is simple. How can I tell PHP to process the string the same way it processes the XML like it does if the XML identifier is used. I have tried to reprocess the string like this:
$new_string = <<<XML
$string
XML;
But no go. Any other ideas?
Are you using file_get_contents to actually load the XML file into a string before using simplexml_load_string which—as the name states—loads XML from a string?
$xml_file = file_get_contents('test.xml');
$xml = simplexml_load_string($xml_file);
echo '<pre>';
print_r($xml);
echo '</pre>';
And the output is good when I use the XML from your post:
SimpleXMLElement Object
(
[#attributes] => Array
(
[xmlnwsa] => http://schemas.xmlsoap.org/ws/2004/08/addressing
[xmlnwsen] => http://schemas.xmlsoap.org/ws/2004/09/enumeration
[xmlnn1] => http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_SystemView
[xmlnxsi] => http://www.w3.org/2001/XMLSchema-instance
)
And so on…
And so on…
And so on…
But that said, I can recreate your error exactly if I add a space or line to the beginning of the XML file like this; note the one simple space before <?xml version="1.0" encoding="UTF-8"?>:
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="http://www.w3.org/2003/05/soap-envelope" xmlnwsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlnwsen="http://schemas.xmlsoap.org/ws/2004/09/enumeration" xmlnn1="http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_SystemView" xmlnxsi="http://www.w3.org/2001/XMLSchema-instance">
And so on…
And so on…
And so on…
And here is my error:
Warning: simplexml_load_string(): Entity: line 1: parser error : XML declaration allowed only at the start of the document in /Applications/MAMP/htdocs/test.php on line 5
Warning: simplexml_load_string(): in /Applications/MAMP/htdocs/test.php on line 5
Warning: simplexml_load_string(): ^ in /Applications/MAMP/htdocs/test.php on line 5
So hey! I know your pain!
Anyway, the quick solution I tried is to use trim on the $xml_file to get rid of extraneous white space at the beginning & end of the of the file like this:
$xml_file = file_get_contents('test.xml');
$xml = simplexml_load_string(trim($xml_file));
echo '<pre>';
print_r($xml);
echo '</pre>';
And all works great!
If I use the following php code to convert an xml to json:
<?php
header("Content-Type:text/json");
$resultXML = "
<QUERY>
<Company>fcsf</Company>
<Details>
fgrtgrthtyfgvb
</Details>
</QUERY>
";
$sxml = simplexml_load_string($resultXML);
echo json_encode($sxml);
?>
I get
{"Company":"fcsf","Details":"\n fgrtgrthtyfgvb\n "}
However, If I use CDATA in the Details element as follows:
<?php
header("Content-Type:text/json");
$resultXML = "
<QUERY>
<Company>fcsf</Company>
<Details><![CDATA[
fgrtgrthtyfgvb]]>
</Details>
</QUERY>
";
$sxml = simplexml_load_string($resultXML);
echo json_encode($sxml);
?>
I get the following
{"Company":"fcsf","Details":{}}
In this case the Details element is blank. Any idea why Details is blank and how to correct this?
This is not a problem with the JSON encoding – var_dump($sxml->Details) shows you that SimpleXML already messed it up before, as you will only get
object(SimpleXMLElement)#2 (0) {
}
– an “empty” SimpleXMLElement, the CDATA content is already missing there.
And after we figured that out, googling for “simplexml cdata” leads us straight to the first user comment on the manual page on SimpleXML Functions, that has the solution:
If you are having trouble accessing CDATA in your simplexml document, you don't need to str_replace/preg_replace the CDATA out before loading it with simplexml.
You can do this instead, and all your CDATA contents will be merged into the element contents as strings.
$xml = simplexml_load_file($xmlfile, 'SimpleXMLElement', LIBXML_NOCDATA);
So, use
$sxml = simplexml_load_string($resultXML, 'SimpleXMLElement', LIBXML_NOCDATA);
in your code, and you’ll get
{"Company":"fcsf","Details":"\n fgrtgrthtyfgvb\n "}
after JSON-encoding it.
I have a PHP page that a service sends out a notice when a donation is made. My PHP page is supposed to grab the XML contents and parse it out for processing.
The service sends the following format:
http://myserver.com/myphp.com?details= xml data
I have the following code listening for this post:
//Load xml from post
$data = file_get_contents('php://input');
$xmlData = simplexml_load_string($data);
//grab mobile number to query mgive for user info
$mnumb= $xmlData->MobileNumber;
$mnumb=ltrim($mnumb,'1');
I am getting the following error when the service sends out the notice.
Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser error : Start tag expected, '<' not found in
what am I missing or coding wrong?
12-18-2013 855cst
Thanks ThW.. Progress is being made.
I used your suggestion #2 to get the data.
When I do a print_r(xmlData), I get no output on the screen. However, when using chrome developer tool, I get the following output:
data=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22utf-8%22%3F%3E%3CGetDonationStatusResult+xmlns%3Axsi%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema-instance%22+xmlns%3Axsd%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%22%3E%3CResultCode+%3E0%3C%2FResultCode%3E%3CResultText+%2F%3E%3CRecordID+%3E0%3C%2FRecordID%3E%3CMobileNumber+%3E12142911111%3C%2FMobileNumber%3E%3CCarrierID+%3E31002%3C%2FCarrierID%3E%3CCarrierName+%3EAT%26amp%3BT+Wireless%3C%2FCarrierName%3E%3CDonationStatus+%3EUserAccepted%3C%2FDonationStatus%3E%3CMobileTransactionID+%3E62622731%3C%2FMobileTransactionID%3E%3CDonationMsgGUID+%3E9c17d57f-b54e-488a-8cf5-1c658d1aa618%3C%2FDonationMsgGUID%3E%3CCampaignID+%3E20409%3C%2FCampaignID%3E%3CShortCode+%3E27722%3C%2FShortCode%3E%3CMsgTime+%3E2013-12-17T12%3A53%3A18%3C%2FMsgTime%3E%3CMessageText+%3ELIBERIA+WAP%3C%2FMessageText%3E%3C%2FGetDonationStatusResult%3E&*
You can see MobileNumber is sent. But, when I echo $mnumb, I get no output. Am I missing something in my use of simplexml_load_string($data); to grab the MobileNumber?
It is not clear where you get the xml data from.
Read from the detail parameter in the url $xml = $_GET['detail'];
Read from the data parameter in the url $xml = $_GET['data'];
Read from the data parameter in the request body (post) $xml = $_POST['data'];
Read the raw post data $xml = file_get_contents("php://input");
Try to var_dump() the data:
var_dump($_GET, $_POST);
After you got the XML into a variable use DOM + Xpath to extract values from it:
$xml = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<GetDonationStatusResult xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema">
<ResultCode >0</ResultCode>
<ResultText />
<RecordID >0</RecordID>
<MobileNumber >19191112222</MobileNumber>
<CarrierID >31002</CarrierID>
<CarrierName >AT&T Wireless</CarrierName>
<DonationStatus >UserAccepted</DonationStatus>
<MsgTime >2013-12-17T20:53:05</MsgTime>
<MessageText >LIBERIA WAP</MessageText>
</GetDonationStatusResult>
XML;
$dom = new DOMDocument();
// try to load the xml
if ($dom->loadXml($xml)) {
$xpath = new DOMXpath($dom);
// read the first MobileNumber element as string
var_dump(
$xpath->evaluate('string(//MobileNumber)')
);
}
Output:
string(11) "19191112222"
Live Result