how to get xml node value php - php

I've fired a curl request. My code is
$URL = "http://demo.com";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xmlLeadCloud");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
Below I am getting the XML in $output variable.
<?xml version="1.0" encoding="utf-16"?>
<LeadCloud>
<InsuranceSvcRs>
<PersHealthPolicyQuoteInqRs>
<MsgStatus>
<MsgStatusCd>Success</MsgStatusCd>
<Payout>17.40</Payout>
<BuyerLeadId>4ded4da790c6fasasasas322</BuyerLeadId>
<BuyerId>34</BuyerId>
</MsgStatus>
</PersHealthPolicyQuoteInqRs>
</InsuranceSvcRs>
</LeadCloud>
How could I get MsgStatusCd element's value from it. So far I've tried.
$s = new SimpleXMLElement($output);
echo $s->InsuranceSvcRs->PersHealthPolicyQuoteInqRs->MsgStatus->MsgStatusCd; die; //not working

Cast the output to a string to get its value:
echo (string) $xml->InsuranceSvcRs->PersHealthPolicyQuoteInqRs->MsgStatus->MsgStatusCd;
You can see from this demo where it prints:
Success

You can use XPath to access this data (see PHP manual entry).
The reason why your accessor does not work is that the XML you are receiving is a data array, hence,
<?xml version="1.0" encoding="utf-16"?>
<LeadCloud> <!-- ROOT -->
<InsuranceSvcRs> <!-- Zero or more -->
<PersHealthPolicyQuoteInqRs> <!-- Zero or more -->
<MsgStatus> <!-- Zero or more -->
<MsgStatusCd>Success</MsgStatusCd> <!-- Zero or one -->
<Payout>17.40</Payout> <!-- Zero or one -->
<BuyerLeadId>4ded4da790c6fasasasas322</BuyerLeadId> <!-- Zero or one -->
<BuyerId>34</BuyerId> <!-- Zero or one -->
</MsgStatus>
</PersHealthPolicyQuoteInqRs>
</InsuranceSvcRs>
</LeadCloud>
and should be accessed as such.

Related

How can I render data from Tally to server application?

I want to render data from tally to my application and vise versa using tally API. When I am using it locally, it is working fine, but I want a solution that when my application is on server connects to tally.
This is the code that I am using with tally API
<?php
$requestXML ='<ENVELOPE>
<HEADER>
<VERSION>1</VERSION>
<TALLYREQUEST> EXPORT</TALLYREQUEST>
<TYPE>COLLECTION</TYPE>
<ID> RTSAllVouchers_FilterForVchNoAndVchType</ID>
</HEADER>
<BODY>
<DESC>
<STATICVARIABLES>
<SVEXPORTFORMAT>$$SysName:XML</SVEXPORTFORMAT>
<!-- TODO : Specify the VoucherNo -->
<RTS_KEY>VCH-INV-1</RTS_KEY>
<!-- TODO : Specify the VoucherType here -->
<RTS_VOUCHERTYPENAME>Sales</RTS_VOUCHERTYPENAME>
</STATICVARIABLES>
<TDL>
<TDLMESSAGE>
<!-- Retrieve all Vouchers for specified VoucherNo and VoucherType -->
<COLLECTION NAME="RTSAllVouchers_FilterForVchNoAndVchType" ISINITIALIZE="Yes">
<TYPE>Voucher</TYPE>
<FETCH>ALLLEDGERENTRIES.*</FETCH>
<FETCH>ALLINVENTORYENTRIES.*</FETCH>
<FILTER>RTS_FilterForVchNoAndVchType</FILTER>
</COLLECTION>
<VARIABLE NAME="RTS_KEY">
<TYPE> String</TYPE>
</VARIABLE>
<VARIABLE NAME="RTS_VOUCHERTYPENAME">
<TYPE>String</TYPE>
</VARIABLE>
<SYSTEM TYPE="FORMULAE" NAME="RTS_FilterForVchNoAndVchType">
$VoucherNumber = $$String:##RTS_KEY and $VoucherTypeName = $$String:##RTS_VOUCHERTYPENAME
</SYSTEM>
</TDLMESSAGE>
</TDL>
</DESC> </BODY></ENVELOPE>';
$server = 'http://localhost:9000/';
$headers = array( "Content-type: text/xml","Content-length:".strlen($requestXML) ,"Connection: close");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
echo " request accepted";
curl_close($ch);
$object = simplexml_load_string($data);print_r($object);
}
?>
$server = 'http://localhost:9000/';
This is the port of the tally its working fine in local.
I heard of the "Tally on cloud" that tally provides, can I render my data from my application to tally using that If yes, then how?

Parameter Missing in XML String

I am passing an xml string to https://insurance-api.pingtree.co.uk/api through curl but is getting parameter error in response (code 12 0) which can be also seen if you browse the above mentioned url.The parameter is defined in the xml i.e. the campaign code then why isn't the system recognizing it. here is my code below which i also got from the http://www.quinternet.com site.
<?php
/**
* Initialize the request xml string here.
* The string in the tag like '[int]' should be replaced with actual value.
* The string in the square brackets is the data type.
*/
$request_string =
'<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:urn="urn:pt_service">
<soapenv:Header />
<soapenv:Body>
<urn:submit
soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<campaign_code>dllfYg0JBwQ</campaign_code>
<site_url>www.surelifecover.co.uk</site_url>
<client_ip>127.0.0.1</client_ip>
<policy_type>J</policy_type>
<cover_purpose>1</cover_purpose>
<cover_amount>50000</cover_amount>
<cover_term>1</cover_term>
<title>1</title>
<first_name>INTRODUCERTEST</first_name>
<last_name>wwww</last_name>
<dob >1995-04-05</dob >
<email>will#bitscube.com</email>
<home_phone>07111111111</home_phone>
<best_call_time>1</best_call_time>
<gender>F</gender>
<is_smoker>Y</is_smoker>
<title2>1</title2>
<first_name2>ww</first_name2>
<last_name2>wwww</last_name2>
<dob2>1991-02-03</dob2>
<email2>913661383#qq.com</email2>
<home_phone2>07111111112</home_phone2>
<best_call_time2>2</best_call_time2>
<gender2>M</gender2>
<is_smoker2>N</is_smoker2>
<terms_consent>Y</terms_consent>
<privacy_content>Y</privacy_consent>
<mode>LIVE</mode>
<keyword>life ins</keyword>
<match_type>1</match_type>
<network>ABC</network>
<device>mobile</device>
<ref>00</ref>
<v1>var1</v1>
<v2>var2</v2>
<v3>var3</v3>
<v4>var4</v4>
<v5>var5</v5>
<i1>1</i1>
<i2>2</i2>
<i3>3</i3>
<i4>4</i4>
<i5>5</i5>
</urn:submit>
</soapenv:Body>
</soapenv:Envelope>
</env:Envelope>';
echo htmlspecialchars($request_string);
echo '<br>';
/**
* The values of the following fields please refer
*to the reference field list spec*
//setup the request headers here, notice at the action string and SOAPAction string */
$request_headers = array('Content-Type: application/soap+xml;charset=utf-8;action="urn:pt_service#Webservice#submit"',
'SOAPAction: "urn:pt_service#Webservice#submit"',
'Content-length: '.strlen($request_string) );
//setup the service url here
$service_url = 'https://insurance-api.pingtree.co.uk/api';
//setup the user agent for the request
$user_agent = $_SERVER['HTTP_USER_AGENT'];
//initialize the curl here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $service_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLINFO_HEADER_OUT, FALSE );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POST,TRUE );
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_POSTFIELDS,$request_string);
curl_setopt($ch, CURLOPT_HTTPHEADER,$request_headers);
//do the submit process here
$result= curl_exec ($ch);
$response_string = curl_exec($ch);
// Convert API feed to xml object
var_dump($response_string);
$xml = simplexml_load_string($response_string);
$name = $xml->response->status;
echo $name;
//-----------------------------------------------
//parsing the response string here
/*example response below. Please get detail
refer for the reponse in specs.
<?xml version="1.0" encoding="UTF8"?>
<response>
<result>20</result>
<status>1</status>
<commission>10.00</commission>
<reference>347</reference>
<message><![CDATA[Accepted]]></message>
<redirect_url>
http://insurance-api.pingtree.co.uk/redirect?p=bUzbir4VhB-BB-Z_gMxVSy8YT15gxUB9iJMBGxi_aOq5PQuDBf_JPqgvc2egv6orCj6TJkeR5g6tX1y0D7hZgbV6DdBAlzbccKmkFNG4-PgWmaNR9LQ57cUQg6jTOXuB
</redirect_url>
</response>
//-----------------------------------------------*/
curl_close($ch);
?>

post xml using curl

i'm trying to post xml via HTTP POST method...the code works fine and displays the desired message.."Data received successfully"..problem is, on looking it up on the backend, the data is not posted on the Agenda Creative backend..where could i have messed up??thanks in advance.
<?php
function sendXmlOverPost($url, $xml) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// For xml, change the content-type.
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned
// Send to remote and return data to caller.
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$postargs = '<?xml version="1.0" encoding="utf-8"?>
<Vacancy>
<Poster>LOGICMELON</Poster>
<Action>Add</Action>
<Username>agendacreative</Username>
<Password>A12!.ndasa55</Password>
<JobReference>AC Test 1</JobReference>
<JobTitle>AC Test 1</JobTitle>
<JobType>F</JobType>
<JobHours>F</JobHours>
<Industry>137</Industry>
<SalaryCurrency>GBP</SalaryCurrency>
<SalaryFrom>100.0000</SalaryFrom>
<SalaryTo>200.0000</SalaryTo>
<SalaryPer>D</SalaryPer>
<SalaryBenefits>Benefits</SalaryBenefits>
<Salary>£100 - 200 per day + Benefits</Salary>
<JobLocation>4</JobLocation>
<JobCountry>GB</JobCountry>
<JobDescription><p>LOGIC MELON TEST VACANCY - PLEASE DO NOT APPLY!!!</p><p>Testing the initial integration to Agenda Creative to make sure that the template is compiled properly andt hat the fields are getting sent through correctly.</p><p>THIS IS A LOGIC MELON TEST VACANCY - PLEASE DO NOT APPLY FOR THIS ROLE AS IT DOES NOT EXIST!!!</p><p>&euro; - Testing Euro Sign</p><p>&pound; - Testing Pound Sign</p></JobDescription>
<ContactName>Logic Melon Support</ContactName>
<ContactEmail>jade.sinclair.1267EC41.0#applythis.net</ContactEmail>
<ApplicationEmail>jade.sinclair.1267EC41.0#applythis.net</ApplicationEmail>
<ApplicationURL></ApplicationURL>
<WeeksToAdvertise>1</WeeksToAdvertise>
</Vacancy>
';
$request = "http://agendacreativerecruitment.co.uk/feed.php";
echo (sendXmlOverPost($request, $postargs));
?>
I don't know about Agenda Creative. But try something like this?
curl_setopt($ch, CURLOPT_POSTFIELDS, array('xml' => $xml));
where 'xml' is the post field your xml data should be in.

PHP Receiving XML

I have a small PHP script that is listening for a POST request. I'm expecting xml, always.
Normally I'm the guy sending the xml requests. But today I'm on the receiving side.
I figured it would be a simple case of listening for a $_POST, but I guess I may be incorrect - I'm getting nothing.
Here's my script that waits for anything xml:
<?php
if(isset($_POST)) {
mail("me#myemail.com","some title i want", print_r($_POST, true));
}else{
die("uh, what happened?");
}
?>
And here is a simple xml string I'm sending from another place:
<?php
$xml_data ='
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don\'t forget me this weekend!</body>
</note>
';
function sendXML2Server($URL,$XML){
$xml_data = trim($XML);
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
echo sendXML2Server('https://someurl.com/inboundxml.php',$xml_data)
?>
And here's what I get in my email:
Array
(
)
I'm guessing I'm not working with an array correctly, but maybe there's something else I'm missing in all this. I'm expecting to get back the actual xml string.
You sending nothing but data, thats why PHP cannot interpreter this data as some key&value. So, you need to send it as a value of variable:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('xml_data' => $xml_data));
or receive as a raw post data:
<?php
if(isset($HTTP_RAW_POST_DATA)) {
mail("me#myemail.com","some title i want", print_r($HTTP_RAW_POST_DATA, true));
}else{
die("uh, what happened?");
}
?>
CURLOPT_POSTFIELDS requires an array:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('content'=>$xml_data));
Then retrieve it like:
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['content'])) {
mail("me#myemail.com","some title i want", print_r($_POST['content'], true));
}else{
die("uh, what happened?");
}
?>

getting parent element's index in xml and php?

I am trying to get the parent element, I think of an XML tag. Basically I need to go through multiple <HotelRoomResponse> results and find this parent tag that contains a child tag with this exact number value: <roomTypeCode>17918</roomTypeCode> I am not sure how to do this or what would be the best way. Because I then need to get ALL the information in that specific <HotelRoomResponse>. Here is an example XML response:
<HotelRoomResponse>
<cancellationPolicy> </cancellationPolicy>
<rateCode>200482409</rateCode>
<roomTypeCode>17918</roomTypeCode>
<rateDescription>
Deluxe Sunset View - All Inclusive-Up to $300Resort Credit
</rateDescription>
<roomTypeDescription>
Deluxe Sunset View - All Inclusive-Up to $300Resort Credit
</roomTypeDescription>
<supplierType>E</supplierType>
</HotelRoomResponse>
So there are various of these result types and I need to loop through it and find this specific one.
Here is how I am connecting to the XML:
$ch = curl_init();
$fp = fopen('room_request.xml','w');
curl_setopt($ch, CURLOPT_URL, "http://api.ean.com/ean-services/rs/hotel/v3/avail?cid=55505&minorRev=13&apiKey=4sr8d8bsn75tpcuja6ypx5g3&locale=en_US&currencyCode=USD&customerIpAddress=10.184.2.9&customerUserAgent=Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit/535.11+(KHTML,+like+Gecko)+Chrome/17.0.963.79+Safari/535.11&customerSessionId=&xml=<HotelRoomAvailabilityRequest><hotelId>".$hid."</hotelId><arrivalDate>05/14/2012</arrivalDate><departureDate>05/18/2012</departureDate><RoomGroup><Room><numberOfAdults>3</numberOfAdults><numberOfChildren>0</numberOfChildren><childAges>0</childAges></Room></RoomGroup><includeDetails>true</includeDetails></HotelRoomAvailabilityRequest>");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FILE, $fp);
$val = curl_exec($ch);
curl_close($ch);//Close curl session
fclose($fp); //Close file overwrite
$avail = simplexml_load_file('room_request.xml');
Any ideas are welcome.
To find all HotelRoomResponse nodes which has a roomTypeCode child node with the value '17918', use the following:
$match = $avail->xpath("/HotelRoomResponse[child::roomTypeCode[text() = '17918']]");
EDIT: $match will be an array holding all matches.
Ok figured it out!!!! Here is what I used to get a node with text = value. Then I got all sibling elements.
// load as file
$contents = new SimpleXMLElement($source,null,true);
$result = $contents->xpath('HotelRoomResponse[roomTypeCode="17918"]');
foreach($result as $key=>$node)
{
$cancelPolicy = $node->cancellationPolicy;
}
$xml = new SimpleXMLElement('room_request.xml');
/* Search for <HotelRoomResponse><roomTypeCode> */
$result = $xml->xpath('/HotelRoomResponse/roomTypeCode');
Result will give you a list of nodes you can then check and get the parent node if appropriate
see here http://www.php.net/manual/en/simplexmlelement.xpath.php
Edit 2.
Key was the namespace
<?php
$ch = curl_init();
$fp = fopen('room_request.xml','w');
curl_setopt($ch, CURLOPT_URL, "http://travellinginmexico.com/test/room_request.xml");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FILE, $fp);
$val = curl_exec($ch);
curl_close($ch);//Close curl session
fclose($fp); //Close file overwrite
$xml = new SimpleXMLElement(file_get_contents('room_request.xml'));
/* Search for <HotelRoomResponse><roomTypeCode> */
$xml->registerXPathNamespace('ns2', 'http://v3.hotel.wsapi.ean.com/');
$result = $xml->xpath("HotelRoomResponse[child::roomTypeCode[text() = '153725']]");
foreach($result as $obj=>$node)
{
var_dump($node->roomTypeCode);
}
With the example you sent will get specific information

Categories