PHP - Format XML Output - php

I'm generating some XML data in response to an HTTP POST request. I'm setting the MIME
header('Content-type: text/xml');
and everything is working well so far.
I'm generating the xml response as follows:
$response = '<?xml version="1.0" encoding="utf-8"?>';
$response .= '<error>';
$response .= '<description>'.$error.'</description>';
$response .= '</error>';
echo $response;
I would now like the format the XML so that instead of seeing this response:
<?xml version="1.0" encoding="utf-8"?><error><description>Login Error: No Username Supplied</description></error>
they see this response:
<?xml version="1.0" encoding="utf-8"?>
<error>
<description>Login Error: No Username Supplied</description>
</error>
I haven't worked with XML output with PHP before so not sure if there's a built in method for doing a "pretty print" type function on the output?

Use the DOM library and set the formatOutput property to true
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElement('error');
$doc->appendChild($root);
$desc = $doc->createElement('description', $error);
$root->appendChild($desc);
echo $doc->saveXML();
Demo ~ https://eval.in/461384

Related

XML Soap body outside of envelope

I have looked at this for hours and really need another set of eyes. My envelope is closed and the body is not showing under it as a child but at a root. Here is the relevant code.
$XMLDoc = new DOMDocument('1.0', 'UTF-8');
$XMLDoc->preserveWhiteSpace = false;
$XMLDoc->formatOutput = true;
// SOAP ENVELOPE ELEMENT AND ATTRIBUTES
$soap = $XMLDoc->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'soap12:Envelope');
$XMLDoc->appendChild($soap);
$soap->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:soap12', 'http://www.w3.org/2003/05/soap-envelope');
$soap->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
$soap->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
// SOAP BODY
$example_element = $XMLDoc->createElement('soap12:Body');
$rootNode = $soap->appendChild($example_element);
and here is the XML it is producing.
<?xml version="1.0" encoding="UTF-8"?>
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
<soap12:Body>

Parsing XML SOAP response in PHP

I have been trying to parse an XML SOAP response in PHP but I continue to get errors. I cannot figure out why these errors are occuring.
Response from the server, stored in $response as a string (with sensitive data removed):
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<h:ServerVersionInfo MajorVersion="15" MinorVersion="20" MajorBuildNumber="323" MinorBuildNumber="19" Version="V2017_10_09" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</s:Header>
<s:Body>
<m:GetAttachmentResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<m:ResponseMessages>
<m:GetAttachmentResponseMessage ResponseClass="Success">
<m:ResponseCode>NoError</m:ResponseCode>
<m:Attachments>
<t:FileAttachment>
<t:AttachmentId Id="id number"/>
<t:Name>message-footer.txt</t:Name>
<t:ContentType>text/plain</t:ContentType>
<t:ContentId>contentid.prod.outlook.com</t:ContentId>
<t:Content>file contents</t:Content>
</t:FileAttachment>
</m:Attachments>
</m:GetAttachmentResponseMessage>
</m:ResponseMessages>
</m:GetAttachmentResponse>
</s:Body>
</s:Envelope>
My code:
$data = simplexml_load_string($response);
$fileData = $data
->children('s:', true)->Body
->children('m:', true)->GetAttachmentResponse->ResponseMessages->GetAttachmentResponseMessage->Attachments
->children('t:', true)->FileAttachment;
I need to be able to get the file name, content type, and content. I continue to get the following error: Node no longer exists (on line 4 here).
For reference, I have been following this guide: https://joshtronic.com/2014/07/13/parsing-soap-responses-with-simplexml/
Any help is greatly appreciated.
I don't know how to read such a complex XML file with simplexml, but I know that DOMDocument works very well for it.
<?php
$source = file_get_contents('file.xml');
$dom = new DOMDocument("1.0", "UTF-8");
$dom->preserveWhiteSpace = false;
$dom->loadXml($source);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
$xpath->registerNamespace("m", "http://schemas.microsoft.com/exchange/services/2006/messages");
$xpath->registerNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
$xpath->registerNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
$xpath->registerNamespace("t", "http://schemas.microsoft.com/exchange/services/2006/types");
$fileAttachments = $xpath->query('//m:GetAttachmentResponseMessage/m:Attachments/t:FileAttachment');
/* #var DOMElement $fileAttachment */
foreach ($fileAttachments as $fileAttachment) {
echo 'Name: ' . $xpath->query('t:Name', $fileAttachment)->item(0)->nodeValue . "\n";
echo 'ContentType: ' . $xpath->query('t:ContentType', $fileAttachment)->item(0)->nodeValue . "\n";
echo 'Content: ' . $xpath->query('t:Content', $fileAttachment)->item(0)->nodeValue . "\n";
}

XML interpretation issue

I am working using soap, when the soap response is sent back all the < and > are represented using special characters.
<?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">
<UploadFileNew_XMLResponse xmlns="http://tempuri.org/GAPS_Uploader/FileUploader">
<UploadFileNew_XMLResult>
<?xml version="1.0" encoding="utf-8"?><Response><ResCode>1009</ResCode><Message>3 transaction(s) failed</Message><Errors><Error><Rownum>1</Rownum><Description>: Reference already exist </Description><Res_Code>59b1ebbc1c012 </Res_Code></Error><Error><Rownum>2</Rownum><Description>: Reference already exist </Description><Res_Code>59cb93d6c1d30 </Res_Code></Error><Error><Rownum>3</Rownum><Description>: Reference already exist </Description><Res_Code>59cbaca456589 </Res_Code></Error></Errors></Response>
</UploadFileNew_XMLResult>
</UploadFileNew_XMLResponse>
</soap:Envelope>
please how can i simplexml_load_string to process this result.
$response = htmlspecialchars_decode($response);
$parser = simplexml_load_string($response);
print_r($parser);
Change the order:
$parser = simplexml_load_string($response);
$response = htmlspecialchars_decode($parser->UploadFileNew_XMLResponse->UploadFileNew_XMLResult);
print_r($response);

I am getting unexpected <head/> in my xml file how to remove that tag

I am generating an api for trip advisor but while sending the xml file an unexpected tag i am getting in production.but i am not getting in localhost.
i have generated xml file using DOM document.
here a copy of my code.
$data=$this->property_model->getreservations_data($start_date,$end_date);
$xml= new DOMDocument("1.0","UTF-8");
$xml->FormatOutput=true;
$Reservations=$xml->createElement('Reservations');
$Reservations=$xml->appendChild($Reservations);
foreach ($data as $key) {
$Reservation=$xml->createElement('Reservation');
$Reservation->setAttribute('property_id',$key['prop_id']);
$Reservation->setAttribute('reservation_id',$key['booking_id']);
$Reservation=$Reservations->appendChild($Reservation);
$EmailAddress=$xml->createElement('EmailAddress',$key['email']);
$EmailAddress=$Reservation->appendChild($EmailAddress);
$fromdate=date('Y-m-d',strtotime($key['travel_from_date']));
$ArrivalDate=$xml->createElement('ArrivalDate',$fromdate);
$ArrivalDate=$Reservation->appendChild($ArrivalDate);
$todate=date('Y-m-d',strtotime($key['travel_to_date']));
$DepartureDate=$xml->createElement('DepartureDate',$todate);
$DepartureDate=$Reservation->appendChild($DepartureDate);
if ($key['order_status']=='Success') {
$Status=$xml->createElement('Status');
$Status->setAttribute('value','reserved');
$Status=$Reservation->appendChild($Status);
}else{
$Status=$xml->createElement('Status');
$Status->setAttribute('value','cancelled');
$Status=$Reservation->appendChild($Status);
}
}
echo $xml->saveXML();
}
output in production:
<?xml version="1.0" encoding="UTF-8"?>
<head/><Reservations><Reservation property_id="998" reservation_id="1998"><EmailAddress>kunal31393#gmail.com</EmailAddress><ArrivalDate>2015-12-07</ArrivalDate><DepartureDate>2018-05-06</DepartureDate><Status value="reserved"/>
output in localhost:
<?xml version="1.0" encoding="UTF-8"?>
<Reservations><Reservation property_id="290" reservation_id="10292"><EmailAddress>yogeshb#gmail.com</EmailAddress><ArrivalDate>2016-10-20</ArrivalDate><DepartureDate>2017-05-17</DepartureDate><Status value="reserved"/>
you need to try sending xml with proper content type
set
header("Content-Type: application/xml");

XML Encoding generated from PHP

I am doing an assignment for class where I have to use a Java Servlet running on Tomcat and have it message a php file to scrape IMDB for movie information and return it as XML to the servlet. It seems to not want to accept any encoding I give it as I continuously get XML tags such as the ones below.
<result cover="url" title="Pokémon" year="1998 TV Series" director="N/A" rating="7.8" details="http://www.imdb.com/title/tt0176385/"/>
Where title of Pokemon should have an accent over the e («é»). I have the following php code to generate the xml. (Important parts only)
<?php header("Content-Type: text/xml; charset=utf-8");
$xml = new DOMDocument();
$rsp = $xml->appendChild($xml->createElement("rsp"));
$xml->encoding = 'utf-8';
$titleNames[$i] = utf8_encode($title_tmp[1]);
$results = $rsp->appendChild($xml->createElement("results"));
$results->setAttribute("total", $tableRows);
$item->setAttribute("title", $titleNames[$i]);
echo $xml->saveXML();
?>
Any help would be greatly appreciated in figuring out how to correctly display special characters!
It's impossible to say what's wrong from your code fragments (which don't even run) but $xml->encoding = 'utf-8' should work. Please compare:
$xml = new DOMDocument();
$rsp = $xml->appendChild($xml->createElement("rsp"));
$rsp->setAttribute("title", 'Pokémon');
echo $xml->saveXML();
/*
<?xml version="1.0"?>
<rsp title="Pokémon"/>
*/
... with:
$xml = new DOMDocument();
$xml->encoding = 'utf-8';
$rsp = $xml->appendChild($xml->createElement("rsp"));
$rsp->setAttribute("title", 'Pokémon');
echo $xml->saveXML();
/*
<?xml version="1.0" encoding="utf-8"?>
<rsp title="Pokémon"/>
*/
(These snippets are expected to be saved as UTF-8).

Categories