I have a problem.
I have 2 php scripts, one which sends xml data using curl and one which is supposed to read the posted data.
The problem is the reciever script is not getting any of the elements in the xml.
Any help would be appriciated.
SENDER SCRIPT:
<?php
$xml = '
<SMS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://api.xxxxxxxxxxxxxxx.co.uk/send/xxxxxxxxxxxxxxx.xsd">
<auth>
<user>yourusername</user>
<pass>yourpassword</pass>
</auth>
<originator>your_sender_name</originator>
<messages>
<msg id="1" gsm="440000000000">
<text>Please come for you appointment tomorrow morning at 12:45</text>
</msg>
<msg id="1" gsm="440000000000">
<text>Please come for you appointment tomorrow morning at 14:00</text>
</msg>
</messages>
</SMS>';
function sendMessages($xml) {
$curl = curl_init();
//$url = "https://sapi.xxxxxxxxxxxxxxx.co.uk/send/xml.php";
$url = "http://api.xxxxxxxxxxxxxxx.co.uk/send/xml.php";
$options = array(CURLOPT_URL => $url, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $xml);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
echo sendMessages($xml);
//echo $xml;
?>
RECIEVER SCRIPT:
<?php
function logResult() {
$postdata = file_get_contents("php://input");
$dom = new DOMDocument();
$dom->loadXML($postdata);
$xp = new domxpath($dom);
$messages = $xp->query("//SMS/auth");
//var_dump($messages);
foreach ($messages as $node) {
//var_dump($node);
return $node->getAttribute('user');
//$node->getAttribute('sentdate');
//$node->getAttribute('donedate');
}
}
echo logResult();
?>
I was unable to get DOMDocument to even load this XML string, with or without the namespace. I have no idea why.
I'd suggest using SimpleXMLElement. I use it a lot, and it works great. I was also able to get it to parse your XML string.
Related
I am trying to make a SOAP request to a service that expects CDATA as part of the request. I managed to do successfull calls using Insomnia with the following, either of the two works:
<ExecuteRequest xmlns="<url>">
<TAG1>
<![CDATA[
<TAG2>
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG3>
<TAG5>TEXT3</TAG5>
</TAG2>
]]>
</TAG1>
</ExecuteRequest>
OR
<ExecuteRequest xmlns="<url>">
<TAG1>
<TAG2>
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG4>
<TAG5>TEXT3</TAG5>
</TAG2>
</TAG1>
</ExecuteRequest>
But I've been having trouble translating the above to work with the php soapclient. For example using the following:
$soapclient = new SoapClient('url?wsdl', array('trace' => 1));
$xmlWriter = new \XMLWriter();
$xmlWriter->openMemory();
$xmlWriter->startElement('TAG1');
$xmlWriter->startElement('TAG2');
$xmlWriter->writeElement('TAG3','TEXT1');
$xmlWriter->writeElement('TAG4','TEXT2');
$xmlWriter->writeElement('TAG5','TEXT3');
$xmlWriter->endElement();
$xmlWriter->endElement();
$myXml = $xmlWriter->outputMemory(true);
$params = array(
new \SoapParam(new \SoapVar($myXml, XSD_ANYXML), 'param')
);
$response = $soapclient->__soapCall('ExecuteRequest',$params);
$lastrequest = $soapclient->__getLastRequest();
$soapclient->__getLastRequest() gives me this output which obviously isn't what I want, no CDATA:
<TAG1>
<TAG2>
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG4>
<TAG5>TEXT3</TAG5>
</TAG2>
</TAG1>
If instead in the xmlwriter I use this to write the CDATA manually:
$xmlWriter->writeCdata('<TAG2>
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG4>
<TAG5>TEXT3</TAG5>
</TAG2>');
Then for some weird reason $soapclient->__getLastRequest() returns the CDATA section commented out and I can't figure out why that is happening:
<TAG1>
<!--[CDATA[<TAG2-->
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG4>
<TAG5>TEXT3</TAG5>
""]]>"
</TAG1>
Notice how TAG2's closing tag is lost as well.
EDIT
The same issue with the CDATA being commented out happens if I don't use the xml writter.
$wholeTag = new \SoapVar("<TAG1><![CDATA[{$text}]]></TAG1>", XSD_ANYXML);
$params = [
'param' => $wholeTag,
];
Any ideas? It's very likely that I'm going about this in the wrong way, so I'm open to any suggestion.
After wasting hours on this I ended up discarding using the soapclient altogether and solved it with Guzzle.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
$xml = new \SimpleXMLElement("<put the whole xml body here, using the Webservice's SOAP 1.1 sample as a reference>");
$xmlstring = $xml->asXML();
$client = new Client();
$url = "< the **full** webservice url (used the Webservice's SOAP 1.1 sample as reference)>";
$action = "action url (used the Webservice's SOAP 1.1 sample as reference)";
try {
$response = $client->post($url,
['headers' =>
['SOAPAction' => $action,
'Content-Type' => 'text/xml; charset=utf-8',
'Host' => "<host url (used the Webservice's SOAP 1.1 sample as reference)>"
],
'body' => $xmlstring
]);
}
catch (GuzzleException $e)
{
return [ 'status' => $e->getResponse()->getStatusCode(), 'message' => $e->getResponse()->getReasonPhrase()];
}
if ($response->getStatusCode() === 200) {
// Success!
return $response->getBody();
}
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetCategoriesJsonResponse xmlns="http://tempuri.org/">
<GetCategoriesJsonResult>[{"code":"0","description":"Sides","storeNumber":"3733"},{"code":"1","description":"Sandwiches","storeNumber":"3733"},</GetCategoriesJsonResult>
</GetCategoriesJsonResponse>
</s:Body>
</s:Envelope>
That is the result of the API, but I want to convert it like:
[
{
"code": "0",
"description": "Sides",
"storeNumber": "3733"
},
{
"code": "1",
"description": "Sandwiches",
"storeNumber": "3733"
},
]
How can I do this? I've tried json_encode and json_decode but it didn't work for me. I have applied different methods to convert it but it's still showing XML results. Can anyone tell me how I can convert it into JSON?
Here's a good answer on available options to working with xml https://stackoverflow.com/a/3577662/3266626
I use FluentDom
$xml = file_get_contents("xml_file.xml");
$doc = new DOMDocument();
$doc->loadXML($xml);
$json = new \FluentDOM\Serializer\Json\RabbitFish($doc);
$object = json_decode($json);
echo "<pre>" . print_r( $object, true) . "</pre>";
echo "<script>console.log({$json})</script>";
Edit: replaced
// PHP Deprecated: Non-static method DOMDocument::loadXML() should not be called statically
$doc = DOMDocument::loadXML($xml);
with
$doc = new DOMDocument();
$doc->loadXML($xml);
I found the solution on that link thanks guys for helping
using api response in this way helps me alot
How to convert SOAP response to PHP Array?
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$body = $xml->xpath('//sBody')[0];
$array = json_decode(json_encode((array)$body), TRUE);
This code is perfectly done thing into JSON
First parse xml and convert data to array:
$xml=(array)simplexml_load_string($myXMLData);
$json_output = $xml['GetCategoriesJsonResult'];
I want to extract url data just like as facebook. For that I am using php DOMDocument.While retrieving the DOM content i.e while retrieving "title" the DOMDocument is returning 0 elements. Here is my code
<?php
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" ?>';
//$url = $_REQUEST["url"];
$url = "http://business.tutsplus.com/articles/how-to-set-up-your-first-magento-store--fsw-43137";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
$data = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument();
#$dom->loadHTML($data);
$title = $dom->getElementsByTagName("title");
//$title = $dom->find("title");
echo "<urlData>";
echo "<title>";
echo $title->length;
echo "</title>";
echo "</urlData>";
?>
Here $title->length is returning 0 elements. What is the problem?
I'm tring to process xml (website) into php array.
I have tried the following code which works for everyting in results but i need to get the totalpage which i'm not able to see how I can do this.
function get_content($url)
/// basically opens the page and stores it as a variable. Buggered if I know how it works!
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();
ob_end_clean();
return $string;
$string = NULL;
$ch = NULL;
$url = NULL;
}
$url = "url";
$content = get_content($url);
$content_x = explode("<result>", $content);
foreach ($content_x as $item)
{
$p1 = strpos($item, '<title>');
$p2 = strpos($item, '</title>');
$l1 = $p2 - $p1;
echo '<br>'.$title = substr($item, $p1, $l1);
}
xml site feed
<?xml version="1.0" encoding="UTF-8"?>
<response version="2">
<totalpage>1005</totalpage>
<results>
<result>
<title>test</title>
<title2>test2</title2>
<title3>test3</title3>
<result>
<result>
<title>test</title>
<title2>test2</title2>
<title3>test3</title3>
<result>
<result>
<title>test</title>
<title2>test2</title2>
<title3>test3</title3>
<result>
........so on
<results>
</response>
I need to get totalpage and everyting in results
How do get totalpage and is they better way to process the results
You absolutely should not be using string manipulation to try to parse XML. There are any number of PHP libraries that can do this. I might recommend SimpleXML.
Usage would be:
$xml = simplexml_load_string($content);
$totalpage = $xml->response->totalpage;
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).