How do I get XML data from a web service using PHP? - php

I need to access the response from a .NET web service which returns data in XML format.
How can I split the data returned? For example, I would like to parse the data into some PHP variables:
$name = "Dupont";
$email = "charles.dupont#societe.com";
I have been looking for how to do this for a long time without finding the correct way to do it.
My script is:
$result = $client->StudentGetInformation($params_4)->StudentGetInformationResult;
echo "<p><pre>" . print_r($result, true) . "</pre></p>";
The echo in my page is:
stdClass Object
(
[any] => 0Successful10371DupontCharlescharles.dupont#societe.com1234charles.dupont#societe.comfalsefr-FR1003FIRST FINANCE1778AAA Département
)
The webservice response format is:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<StudentGetInformationResponse xmlns="http://tempuri.org/">
<StudentGetInformationResult>xml</StudentGetInformationResult>
</StudentGetInformationResponse>
</soap:Body>
</soap:Envelope>
I have tried your example. But it doesn't do what i need.
I need to split the value returned. I would like to get the data and put them into PHP variables:
$name = "Dupont";
$email = "charles.dupont#societe.com";
etc...
Unfortunately the echo of your example gives:
object(stdClass)#1 (1) { ["StudentGetInformationResult"]=> object(stdClass)#11 (1) { ["any"]=> string(561) "0Successful10371DupontCharlescharles.dupont#societe.com1234charles.dupont#societe.comfalsefr-FR1003FIRST FINANCE1778AAA Département" } }

The only class you need is SoapClient. There are a lot of examples you can use in the PHP Documentation.
Example:
try {
$client = new SoapClient ( "some.aspx?wsdl" );
$result = $client->StudentGetInformation ( $params_4 );
$xml = simplexml_load_string($result->StudentGetInformationResult->any);
echo "<pre>" ;
foreach ($xml as $key => $value)
{
foreach($value as $ekey => $eValue)
{
print($ekey . " = " . $eValue . PHP_EOL);
}
}
} catch ( SoapFault $fault ) {
trigger_error ( "SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR );
}
Output
Code = 0
Message = Successful
stud_id = 10373
lname = Dupont
fname = Charles
loginid = charles.dupont#societe.com
password = 1234
email = charles.dupont#societe.com
extid =
fdisable = false
culture = fr-FR
comp_id = 1003
comp_name = FIRST FINANCE
dept_id = 1778
dept_name = Certification CMF (Test web service)
udtf1 =
udtf2 =
udtf3 =
udtf4 =
udtf5 =
udtf6 =
udtf7 =
udtf8 =
udtf9 =
udtf10 =
Audiences =

Related

XML Parsing in PHP (using simplexml_load_string)

I have the following code and I have been working to try to get this working.
<?php declare(strict_types=1);
$session_token = '?'; $xml = '';
$result = '<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://ws.careerbuilder.com/resumes/"><Packet><Errors /><SessionToken>3msk323msd-3312-CQ-2</SessionToken></Packet></string>
';
if ($result) {
$xml = simplexml_load_string($result);
print_r($xml);
if ($xml !== false) {
$session_token = $xml->SessionToken;
echo PHP_EOL.'Session: '. $session_token;
} else {
echo 'Error: XML does NOT appear to be valid';
}
} else
echo 'Error: result does NOT appear be valid';
The problem is no matter what I'm not able to extract the <SessionToken> value from the XML. When I use print_r() I get the following:
SimpleXMLElement Object
(
[0] => <Packet><Errors /><SessionToken>3msk323msd-3312-CQ-2</SessionToken></Packet>
)
Your input is entity-encoded. If this is really what it looks like, you'll need to decode it first:
$xml = simplexml_load_string(html_entity_decode($result));
$token = (string) $xml->Packet->SessionToken[0];
You document contains nested XML. The text content of the string element is serialized XML. So you need to parse it after reading it.
$result = '<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://ws.careerbuilder.com/resumes/"><Packet><Errors /><SessionToken>3msk323msd-3312-CQ-2</SessionToken></Packet></string>
';
$string = new SimpleXMLElement($result);
$packet = new SimpleXMLElement((string)$string);
var_dump($packet);
Output:
object(SimpleXMLElement)#2 (2) {
["Errors"]=>
object(SimpleXMLElement)#3 (0) {
}
["SessionToken"]=>
string(20) "3msk323msd-3312-CQ-2"
}

php parse xml from url

http://api.hostip.info/?ip=87.14.94.152
From this link (xml) i am tried to retrive countryName and countryAbbrev like this:
$url = 'http://api.hostip.info/?ip=87.14.94.152';
$xml = simplexml_load_file($url) or die("feed not loading");
$Country = $xml->gml['featureMember']->Hostip->countryName;
echo $Country;
echo 'BREAK HTML';
echo "-----";
echo "// "; var_dump($xml); echo " //";
but $Country is blank, any idea about?
thanks in advance
Try this not like an answer, but, just another way to do the same:
$data = file_get_contents('http://api.hostip.info/get_html.php?ip=87.14.94.152&position=true');
$arrayofdata = explode("\n", $data);
$country = explode(":", $arrayofdata[0]);
$count = explode(" ", $country[1]);
echo "Country Name: ".$count[1]."</br>"; //Prints ITALY
echo "Country Abbv: ".trim($count[2],"()"); //Prints IT
The position=true url part, it's just in case that you want to retrieve the coordinates.
Cheers ;)
Try this:
$url = 'http://api.hostip.info/?ip=87.14.94.152';
$xml = simplexml_load_file($url) or die("feed not loading");
$fm=$xml->xpath('//gml:featureMember');
print_r($fm[0]->Hostip->countryName);
Make a local copy of the xml and it will work. Just tested this and got the data back:
$url = 'http://api.hostip.info/?ip=87.14.94.152';
$data = file_get_contents($url);
$xml = simplexml_load_file($data) or die("feed not loading");
The countryName node is nested in a deeper level. You can use the children() method to access attributes with colon. Here's how you can get the country name:
$countryName = (string) $xml->children('gml', true)
->featureMember->children('', true)
->Hostip->countryName; // => ITALY
You could also use an XPath expression to retrieve the country name. This is easier:
$hostip = $xml->xpath('//Hostip');
$countryName = $hostip[0]->countryName; // => ITALY
$countryAbbrev = $hostip[0]->countryAbbrev; // => IT
protected function getCountryNameFromIP()
{
$ip = $_SERVER['REMOTE_ADDR'];
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$answerIP = #file_get_contents("http://api.ipinfodb.com/v3/ip-country/?key=4b585e37503a519a408dc17878e6ec04fa963e1b946c567722538d9431c2d5cb&format=xml&ip=$ip" ,false,$context);
if(isset($answerIP) && $answerIP !="")
{
$theResJ = simplexml_load_string($answerIP);
$last_login_ip_cn = $theResJ->countryName;
/**
* $last_login_ip_cc = $theResJ->countryCode;
* $last_login_ip_rc = $theResJ->regionCode;
* $last_login_ip_rn = $theResJ->regionName;
* $last_login_ip_cp = $theResJ->cityName;
* $last_login_ip_lat = $theResJ->latitude;
* $last_login_ip_lng = $theResJ->longitude;
* $last_login_zip_code= $theResJ->zipCode;
*/
}
else
{
$last_login_ip_cn = "";
/**
* $last_login_ip_cc = "";
* $last_login_ip_rc = "";
* $last_login_ip_rn = "";
* $last_login_ip_cp = "";
* $last_login_ip_lat = "";
* $last_login_ip_lng = "";
* $last_login_zip_code= "";
*/
}
return $last_login_ip_cn;
}
I hope it helps you
I agree. I just tried both answers and got good results. Here is the test code I just ran:
<?php
$url = 'http://api.hostip.info/?ip=87.14.94.152';
// $data = file_get_contents($url);
$xml = simplexml_load_file($url) or die("feed not loading");
// $Country = $xml->gml['featureMember']->Hostip->countryName;
// echo $Country;
echo 'BREAK HTML';
echo "-----";
echo "// "; var_dump($xml); echo " //<br/>";
?><br/><?php
var_dump($xml->gml);
?><br/><?php
print_r($xml);
?><br/><?php
var_dump((string) $xml->gml->featureMember->Hostip->countryName);
?><br/><?php
echo $xml->gml['featureMember']->Hostip->countryName;
$Country = (string) $xml->children('gml', true)
->featureMember->children('', true)
->Hostip->countryName; // => ITALY
echo $Country;
$fm=$xml->xpath('//gml:featureMember');
print_r($fm[0]->Hostip->countryName);
and here are the results output:
BREAK HTML-----// object(SimpleXMLElement)#1 (1) { ["#attributes"]=> array(1) { ["version"]=> string(5) "1.0.1" } } //
object(SimpleXMLElement)#2 (0) { }
SimpleXMLElement Object ( [#attributes] => Array ( [version] => 1.0.1 ) )
string(0) ""
ITALYSimpleXMLElement Object ( [0] => ITALY )

webservice not returning a array

I need help with this webservice, it is returning this stdClass Object ( [GETOfertasAereasResult] => )
I need to return an array with all the values.
<?php
try {
$wsdl_url = 'http://portaldoagente.com.br/wsonlinetravel/funcoes.asmx?WSDL';
$client = new SOAPClient($wsdl_url);
$params = array(
'sLojaChave' => "Y2Y4ZGRkOWU=",
);
$return = $client->GETOfertasAereas($params);
print_r($return);
} catch (Exception $e) {
echo "Exception occured: " . $e;
}
?>
Assuming your data is like the following:
$return = '<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org /2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<GETOfertasAereasResponse xmlns="http://tempuri.org/">
<GETOfertasAereasResult>Some result content</GETOfertasAereasResult>
</GETOfertasAereasResponse>
</soap12:Body>
</soap12:Envelope>';
Try this:
$obj = new SimpleXMLElement($return);
$body = $obj->children('soap12', true)->Body->children();
$content = (string) $body->GETOfertasAereasResponse->GETOfertasAereasResult;
var_dump($content);

simplexml_load_string unable to retrieve values

I am trying to get the value in ResponseId and MAP_IMAGE_ZOOM1000 but i receive empty responses from var_dump.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org /soap/envelope/">
<soapenv:Header xmlns:get="http://tnb.com.my/CGIS/D/getcustareasnapshotpro" xmlns:bsm="http://www.tnb.com.my/CGIS/schemas/bsmfpro" xmlns:cgis="http://tnb.com.my/CGIS/D/cgis_cmccustomermgnt"/>
<soapenv:Body xmlns:get="http://tnb.com.my/CGIS/D/getcustareasnapshotpro" xmlns:bsm="http://www.tnb.com.my/CGIS/schemas/bsmfpro" xmlns:cgis="http://tnb.com.my/CGIS/D/cgis_cmccustomermgnt">
<get1:GetCustAreaSnapshotResponseParam xmlns:get1="http://tnb.com.my/CGIS/D/getcustareasnapshotcon">
<ResponseHdr>
<bsm:ResponseId>gero etgero etgero etgero etgero</bsm:ResponseId>
<bsm:ResTransactionId>123456789012345</bsm:ResTransactionId>
<bsm:ProviderId>CGIS</bsm:ProviderId>
<bsm:ResTimestamp>2004-02-15T02:44:14</bsm:ResTimestamp>
<bsm:ResStatus>SUCC</bsm:ResStatus>
<bsm:MsgCode>IM-001</bsm:MsgCode>
<bsm:MsgDesc>Success</bsm:MsgDesc>
</ResponseHdr>
<ResGetCustAreaSnapshot>
<cmc:GetCustAreaSnapshot xmlns:cmc="http://tnb.com.my/CGIS/D/cmc_customermgnt">
<cmc:MAP_IMAGE_ZOOM1000>abc</cmc:MAP_IMAGE_ZOOM1000>
</cmc:GetCustAreaSnapshot>
</ResGetCustAreaSnapshot>
</get1:GetCustAreaSnapshotResponseParam>
$Envelope = simplexml_load_string($responseXml);
$Envelope->registerXPathNamespace('soap','http://schemas.xmlsoap.org/soap/envelope/');
$Envelope->registerXPathNamespace('bsm','http://www.tnb.com.my/CGIS/schemas/bsmfpro/');
$Envelope->registerXPathNamespace('cmc','http://tnb.com.my/CGIS/D/cgis_cmccustomermgnt/');
$Envelope->registerXPathNamespace('get','http://tnb.com.my/CGIS/D/getcustareasnapshotcon/');
$result = $Envelope->xpath('soap:Envelope/soap:Body/get:GetCustAreaSnapshotResponseParam/ResponseHdr/bsm:ResponseId');
var_dump($result);
die;
any help would be much appreciated. Thank You !!
For some reason the last ResponseId is not working for me.
However, I "cheated", and I can select the first child of ResponseHdr:
$result = $Envelope->xpath('//soapenv:Envelope/soapenv:Body/get1:GetCustAreaSnapshotResponseParam/ResponseHdr/*[1]');
Edit: Here is the best I was able to do with SimpleXML. I'm going to try DOMDocument though, as it may be a better alternative.
$result = $Envelope->xpath('//soapenv:Envelope/soapenv:Body/get1:GetCustAreaSnapshotResponseParam/ResponseHdr');
foreach( $result[0]->children('bsm', true) as $node) var_dump( $node->getName() . ' = ' . (string) $node);
$result = $Envelope->xpath('//soapenv:Envelope/soapenv:Body/get1:GetCustAreaSnapshotResponseParam/ResGetCustAreaSnapshot/*[1]');
foreach( $result[0]->children('cmc', true) as $node) var_dump( $node->getName() . ' = ' . (string) $node);
Given the above code, I was able to get the following output:
string(45) "ResponseId = gero etgero etgero etgero etgero"
string(34) "ResTransactionId = 123456789012345"
string(17) "ProviderId = CGIS"
string(34) "ResTimestamp = 2004-02-15T02:44:14"
string(16) "ResStatus = SUCC"
string(16) "MsgCode = IM-001"
string(17) "MsgDesc = Success"
string(24) "MAP_IMAGE_ZOOM1000 = abc"
Try this:
Save it as ns.xml
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header xmlns:get="http://tnb.com.my/CGIS/D/getcustareasnapshotpro" xmlns:bsm="http://www.tnb.com.my/CGIS/schemas/bsmfpro" xmlns:cgis="http://tnb.com.my/CGIS/D/cgis_cmccustomermgnt"/>
<soapenv:Body xmlns:get="http://tnb.com.my/CGIS/D/getcustareasnapshotpro" xmlns:bsm="http://www.tnb.com.my/CGIS/schemas/bsmfpro" xmlns:cgis="http://tnb.com.my/CGIS/D/cgis_cmccustomermgnt">
<get1:GetCustAreaSnapshotResponseParam xmlns:get1="http://tnb.com.my/CGIS/D/getcustareasnapshotcon">
<ResponseHdr>
<bsm:ResponseId>gero etgero etgero etgero etgero</bsm:ResponseId>
<bsm:ResTransactionId>123456789012345</bsm:ResTransactionId>
<bsm:ProviderId>CGIS</bsm:ProviderId>
<bsm:ResTimestamp>2004-02-15T02:44:14</bsm:ResTimestamp>
<bsm:ResStatus>SUCC</bsm:ResStatus>
<bsm:MsgCode>IM-001</bsm:MsgCode>
<bsm:MsgDesc>Success</bsm:MsgDesc>
</ResponseHdr>
<ResGetCustAreaSnapshot>
<cmc:GetCustAreaSnapshot xmlns:cmc="http://tnb.com.my/CGIS/D/cmc_customermgnt">
<cmc:MAP_IMAGE_ZOOM1000>abc</cmc:MAP_IMAGE_ZOOM1000>
</cmc:GetCustAreaSnapshot>
</ResGetCustAreaSnapshot>
</get1:GetCustAreaSnapshotResponseParam>
</soapenv:Body>
</soapenv:Envelope>
PHP Code to get the nodes:
<?php
$xml = simplexml_load_file( 'ns.xml' );
$xml->registerXPathNamespace('b', 'http://www.tnb.com.my/CGIS/schemas/bsmfpro');
$xml->registerXPathNamespace('c', 'http://tnb.com.my/CGIS/D/cmc_customermgnt');
$xpath = $xml->xpath( '//b:ResponseId | //c:MAP_IMAGE_ZOOM1000' );
foreach( $xpath as $key => $value ) {
// echo the node name and its value
echo $value->getName() . ' => ' . $value . "\n<br>";
}
?>
Hope this helps.

how to load xml from this code please

I want to load the inside values from this xml code:
<?xml version="1.0" encoding="UTF-8"?>
<geoPlugin>
<geoplugin_city>Salt Lake City</geoplugin_city>
<geoplugin_region>UT</geoplugin_region>
<geoplugin_areaCode>801</geoplugin_areaCode>
<geoplugin_dmaCode>770</geoplugin_dmaCode>
<geoplugin_countryCode>US</geoplugin_countryCode>
<geoplugin_countryName>United States</geoplugin_countryName>
<geoplugin_continentCode>NA</geoplugin_continentCode>
<geoplugin_latitude>40.700199127197</geoplugin_latitude>
<geoplugin_longitude>-111.94339752197</geoplugin_longitude>
<geoplugin_regionCode>UT</geoplugin_regionCode>
<geoplugin_regionName>Utah</geoplugin_regionName>
<geoplugin_currencyCode>USD</geoplugin_currencyCode>
<geoplugin_currencySymbol>$</geoplugin_currencySymbol>
<geoplugin_currencyConverter>1</geoplugin_currencyConverter>
</geoPlugin>
If you can see the geoplugin_city, etc
I want to load these values to php
$location = 'http://www.geoplugin.net/xml.gp?ip='.$_SERVER['REMOTE_ADDR'];
$xml = simplexml_load_file($location);
that didn't work.
please help me out.
opps php i ment xml
It's not outputting XML, it's outputting serialized PHP data:
$location = 'http://www.geoplugin.net/php.gp?ip=192.168.1.1';
$file = unserialize(file_get_contents($location));
print_r($file);
Change your code to this first
$location = 'http://www.geoplugin.net/xml.gp?ip='.$_SERVER['REMOTE_ADDR'];
$xml = simplexml_load_file($location);
After that, make a Foreach loop to have all the data from that.
foreach ($xml as $keys => $values) {
$data[] = $values; // $data array have all your data independently.
}
Now, print the array and test the values.
echo "<pre>"; print_r($data); echo "</pre>";
However, try for dumping the variables so you will get the data types too..
var_dump($xml);
You will want to use the XML api instead of the PHP api.
$location = 'http://www.geoplugin.net/xml.gp?ip='.$_SERVER['REMOTE_ADDR'];
$xml = simplexml_load_file($location);
If you want the values in PHP, I would recommend not using the XML library at all.
$data = unserialize(file_get_contents('http://www.geoplugin.net/php.gpip='.$_SERVER['REMOTE_ADDR'])));
//Then access the data directly.
echo $data['geoplugin_city'];
echo $data['geoplugin_region'];
if you want to call the xml API the URL is
$location = 'http://www.geoplugin.net/xml.gp?ip='.$_SERVER['REMOTE_ADDR'];
$xml = simplexml_load_file($location);
Output Sample
<?xml version="1.0" encoding="UTF-8"?>
<geoPlugin>
<geoplugin_city>Lagos</geoplugin_city>
<geoplugin_region>Lagos</geoplugin_region>
<geoplugin_areaCode>0</geoplugin_areaCode>
<geoplugin_dmaCode>0</geoplugin_dmaCode>
<geoplugin_countryCode>NG</geoplugin_countryCode>
<geoplugin_countryName>Nigeria</geoplugin_countryName>
<geoplugin_continentCode>AF</geoplugin_continentCode>
<geoplugin_latitude>6.4531002044678</geoplugin_latitude>
<geoplugin_longitude>3.395800113678</geoplugin_longitude>
<geoplugin_regionCode>05</geoplugin_regionCode>
<geoplugin_regionName>Lagos</geoplugin_regionName>
<geoplugin_currencyCode>NGN</geoplugin_currencyCode>
<geoplugin_currencySymbol>₦</geoplugin_currencySymbol>
<geoplugin_currencyConverter>157.6899963379</geoplugin_currencyConverter>
</geoPlugin>
EDIT 1
echo "<pre>";
foreach($xml as $key => $value)
{
echo $key , " = " , $value , "\n" ;
}
Output
geoplugin_city = Lagos
geoplugin_region = Lagos
geoplugin_areaCode = 0
geoplugin_dmaCode = 0
geoplugin_countryCode = NG
geoplugin_countryName = Nigeria
geoplugin_continentCode = AF
geoplugin_latitude = 6.4531002044678
geoplugin_longitude = 3.395800113678
geoplugin_regionCode = 05
geoplugin_regionName = Lagos
geoplugin_currencyCode = NGN
geoplugin_currencySymbol = ₦
geoplugin_currencyConverter = 157.6899963379
Thanks
:)

Categories