As I haven't found a solution for testing my SOAP integration, I have decided to make my own soap requests through POST method. The method sends an XML response which works fine, but I want to make my own array-to-xml parser. So far my code is:
private function parseData($xml, $data) {
foreach ($data as $key => $row) {
var_dump($key, $row);
if (is_array($row) && count($row)) {
return $this->parseData($xml, $row);
}
$xml->addChild($key, $row);
}
return $xml;
}
private function toWSDL($call, $data) {
$root = '<data/>';
$xml = new \SimpleXMLElement($root);
$xml = $this->parseData($xml, $data);
$xmlBody = $xml->asXML();
$open = '<ns1:' . $call . '>';
$close = '</ns1:' . $call . '>';
$xmlBody = str_replace('<data>', $open, $xmlBody);
$xmlBody = str_replace('</data>', $close, $xmlBody);
$xmlBody = str_replace('<?xml version="1.0"?>', '', $xmlBody);
$request_data = <<<EOF
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="https://api.hostedshop.io/service.php">
<SOAP-ENV:Body>
$xmlBody
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
EOF;
return $request_data;
}
but it does not work for a soap function called "Product_Update", which takes in an array like so:
$this->call("Product_Update", [
"ProductData" => [
"Id" => 1,
"Stock" => 2
]
]);
The "ProductData" key with an array does not work with my parseData function, which is why I am writing for help.
Related
I have the object in php like this:
object(stdClass)[16]
public 'L1' =>
object(stdClass)[17]
public 'int' =>
array (size=2)
0 => int 1
1 => int 2
public 'L2' => string '52' (length=2)
public 'R' => string '2' (length=1)
Which i can convert to XML and i get:
<data>
<L1>
<int>
<node>1</node>
<node>2</node>
</int>
</L1>
<L2>52</L2>
<R>2</R>
</data>
The problem is that i want to get rid of the names of the nodes and the node . In the final i want my XML to look like this:
<data>
<param1>1</param1>
<param2>2</param2>
<param3>52</param3>
<param4>2</param4>
</data>
Can anyone suggest the way i can do it ?
Thank you in advance.
Here is the class for creating the XML:
<?php
class XMLSerializer {
// functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/
public static function generateValidXmlFromObj(stdClass $obj, $node_block='data', $node_name='node') {
$arr = get_object_vars($obj);
return self::generateValidXmlFromArray($arr, $node_block, $node_name);
}
public static function generateValidXmlFromArray($array, $node_block='data', $node_name='node') {
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '<' . $node_block . '>';
$xml .= self::generateXmlFromArray($array, $node_name);
$xml .= '</' . $node_block . '>';
return $xml;
}
private static function generateXmlFromArray($array, $node_name) {
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES);
}
return $xml;
}
}
And the code:
header ("Content-Type:text/xml");
include 'tamo.wss.php';
include 'xml_class.php';
$user = $_GET['id'];
$client = new SoapClient("Wsdl_Service", $options);
$client->__setSoapHeaders(Array(new WsseAuthHeader("login", "password")));
$param['ns1:l0'] = $user;
$encodded = new SoapVar($param, SOAP_ENC_OBJECT);
$result = $client->GetAttributes($encodded);
$xml = XMLSerializer::generateValidXmlFromObj($result->GetAttributesResult->Result->SingleAttribute);
echo $xml;
If I've understood your problem correctly, you can solve it this way.
$index = 1;
$xml = '<data>';
foreach(get_object_vars($result->GetAttributesResult->Result->SingleAttribute) as $value) {
$xml .= '<param' . $index . '>' . $value . '</param' . $index++ . '>';
}
$xml .= '</data>';
I have following array in PHP and I want to convert it equivalent XML.
$data = array("VitalParameters"=>array(
"Details"=>array(
"PID"=>1234,
"OPID"=>1345
),
"Parameters"=>array(
"HR"=>112,
"SPO2"=>0
)));
Following XML tree structure which I expected
<VitalParameters>
<Details>
<PID>1234</PID>
<OPID>1345</OPID>
</Details>
<Parameters>
<HR>112</HR>
<SPO2>0</SPO2>
</Parameters>
</VitalParameters>
I tried many things but no luck. If any more information required just comment I will give additional information.
Try Array2XML (http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes) this has worked for me.
$data = array(
"Details" => array(
"PID" => 1234,
"OPID" => 1345
),
"Parameters" => array(
"HR" => 112,
"SPO2" => 0
));
$xml = Array2XML::createXML('VitalParameters', $data)->saveXML();
echo $xml;
Output
<?xml version="1.0" encoding="UTF-8"?>
<VitalParameters>
<Details>
<PID>1234</PID>
<OPID>1345</OPID>
</Details>
<Parameters>
<HR>112</HR>
<SPO2>0</SPO2>
</Parameters>
</VitalParameters>
This should get you on the right track, probably needs some tuning though (especially in regards to keys aswell as checking if $arr is an array/object in the first place... this was just to show you how to recursively iterate them and print the data).
Also, this snippet does not support XML attributes in any way.
<?php
$data = array("VitalParameters"=>array(
"Details"=>array(
"PID"=>1234,
"OPID"=>1345
),
"Parameters"=>array(
"HR"=>112,
"SPO2"=>0
)));
function ArrayToXML($arr, $depth = 0, $maxDepth = 2)
{
$retVal = "";
foreach($arr as $key => $value)
{
$retVal .= "<" . $key . ">";
$type = gettype($value);
switch($type)
{
case "array":
case "object":
if ($depth < $maxDepth)
$retVal .= ArrayToXml($value, $depth+1, $maxDepth);
else
$retVal .= $type; // Depth >= MaxDepth, not iterating here
break;
case "boolean":
$retVal .= $value ? "true" : "false";
break;
case "resource":
$retVal .= "Resource";
case "NULL":
$retVal .= "NULL";
default:
$retVal .= $value;
}
$retVal .= "</" . $key . ">\n";
}
return $retVal;
}
echo ArrayToXML($data);
?>
Output:
<VitalParameters><Details><PID>1234</PID>
<OPID>1345</OPID>
</Details>
<Parameters><HR>112</HR>
<SPO2>0</SPO2>
</Parameters>
</VitalParameters>
I got solution like following code
<?php
header("Content-type: text/xml; charset=utf-8");
$data = array(
"Details" => array(
"PID" => "1234","OPID" => "1345"
),"Parameters" => array(
"HR" => "112","SPO2" => "0"
)
);
$domtree = new DOMDocument('1.0', 'UTF-8');
/* create the root element of the xml tree */
$xmlRoot = $domtree->createElement("VitalParameters");
/* append it to the document created */
$xmlRoot = $domtree->appendChild($xmlRoot);
foreach ($data as $key=>$value)
{
$currentElement= $domtree->createElement($key);
$currentElement= $xmlRoot->appendChild($currentElement);
if(is_array($value))
{
foreach ($value as $k=>$v)
{
$currentElement->appendChild($domtree->createElement($k,$v));
}
}
}
/* get the xml printed */
echo $domtree->saveXML();
Output
<VitalParameters>
<Details>
<PID>1234</PID>
<OPID>1345</OPID>
</Details>
<Parameters>
<HR>112</HR>
<SPO2>0</SPO2>
</Parameters>
</VitalParameters>
I think - this is must be more simple:
function arrayToXML($arr){
$s = "";
foreach($arr as $k => $v){
if(is_array($v)){$v = arrayToXML($v);}
$s .= "<{$k}>{$v}</{$k}>";
}
return $s;}
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);
Fatal error: Call to a member function registerXPathNamespace() on a non-object in /home/gateway/public_html/index.php on line 83
So the error I am getting is above, and on that line is the following
$host = "services.incard.com.au/telechoicetransservice.asmx";
$timestamp = getGMTtimestamp();
$vars =
"<?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>" .
"<ProcessPayment xmlns=\"https://services.incard.com.au\">".
"<auth>" .
"<AccountCode>". urlencode($_POST['AccountCode'])."</AccountCode>".
"<Username>". urlencode($_POST['AccountCode'])."</Username>".
"<Password>". urlencode($_POST['AccountCode'])."</Password>".
"</auth>" .
"<MerchantNumber>".urlencode($_POST['MerchantNumber'])."</MerchantNumber>" .
"<CustomerNumber>".urlencode($_POST['CustomerNumber'])."</CustomerNumber>".
"<Amount>".urlencode($_POST['Amount'])."</Amount>".
"<Description>".urlencode($_POST['Description'])."</Description>".
"</ProcessPayment>".
"</soap:Body></soap:Envelope>";
$response = openSocket($host, $vars);
$xmlres = array();
$xmlres = makeXMLTree ($response);
$xml = simplexml_load_string($response);
$xml->registerXPathNamespace('soap:Envelope', 'http://schemas.xmlsoap.org/soap/envelope/');
foreach ($xml->xpath('//soap:Envelope:ResponseCode') as $item) {
echo (string) $item;
}
foreach ($xml->xpath('//soap:Envelope:ResponseDescription') as $item) {
echo (string) $item;
}
I can't figure out why it is not working.
The response we get back from the server that we are requesting is the following
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?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>
<ProcessPaymentResponse xmlns="https://services.incard.com.au">
<ProcessPaymentResult>
<ResponseCode>string</ResponseCode>
<ResponseDescription>string</ResponseDescription>
</ProcessPaymentResult>
</ProcessPaymentResponse>
</soap:Body>
</soap:Envelope>
Try replacing
<?php
$xml->registerXPathNamespace('soap:Envelope',
'http://schemas.xmlsoap.org/soap/envelope/');
foreach ($xml->xpath('//soap:Envelope:ResponseCode') as $item) {
echo (string) $item;
}
foreach ($xml->xpath('//soap:Envelope:ResponseDescription') as $item) {
echo (string) $item;
}
?>
with
<?php
$xml->registerXPathNamespace( 'soap',
'http://schemas.xmlsoap.org/soap/envelope/' );
$result = $xml->xpath('//soap:Body');
foreach ($result as $body) {
echo $body->ProcessPaymentResponse->ProcessPaymentResult->ResponseCode . "<br />";
echo $body->ProcessPaymentResponse->ProcessPaymentResult->ResponseDescription . "<br />";
}
?>
Hope this helps.
I want to modify an RSS feed. I want to remove X items from feed and then return the new feed as XML.
<?php
class RSS {
private $simpleXML;
public function __construct($address) {
$xml = file_get_contents($address);
$this->simpleXML = simplexml_load_string($xml);
}
private function getRssInformation() {
// Here I want to get the Rss Head information ...
}
// Here I get X items ...
private function getItems($itemsNumber, $UTF8) {
$xml = null;
$items = $this->simpleXML->xpath('/rss/channel/item');
if(count($items) > $itemsNumber) {
$items = array_slice($items, 0, $itemsNumber, true);
}
foreach($items as $item) {
$xml .= $item->asXML() . "\n";
}
return $xml;
}
public function getFeed($itemsNumber = 5, $UTF8 = true) {
// Here i will join rss information with X items ...
echo $this->getItems($itemsNumber, $UTF8);
}
}
?>
Is it possible with XPath?
Thank you.
Another way to do it (but could be cleaner) :
private function getItems($itemsNumber, $UTF8) {
$xml = '<?xml version="1.0" ?>
<rss version="2.0">
<channel>';
$i = 0;
if (count($this->simpleXML->rss->channel->item)>0){
foreach ($this->simpleXML->rss->channel->item as $item) {
$xml .= str_replace('<?xml version="1.0" ?>', '', $item->asXML());
$i++;
if($i==$itemsNumber) break;
}
}
$xml .=' </channel></rss> ';
return $xml;
}
But I think asXML(); add the XML declaration :
<?xml version="1.0" ?>
I edited my code. It's dirty but it should work. Any better idea?