XML Parsing Error: junk after document element in Twilio - php

I am running the following code, and it is showing me this error. Can someone tell me why is my xml giving a problem? When i run this in the browser I get:
XML Parsing Error: junk after document element
When I run this through Twiilio I get the following error
parserMessage Error on line 2 of document : Content is not allowed in prolog.
<?php
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
require "twilio-php-latest/Services/Twilio.php";
/* Set our AccountSid and AuthToken */
$AccountSid = "xxxxx";
$AuthToken = "xxxx";
include 'db.php';
$caller=$_REQUEST['From'];
/* Instantiate a new Twilio Rest Client */
$client = new Services_Twilio($AccountSid, $AuthToken);
$from= "+17864310795";
$student_number=substr($caller,1);
$db = new PDO("mysql:host=localhost;dbname=xxxx","xxxx","xxxx");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$studentData=getSingleStudentData($db,$student_number);
foreach($studentData as $key=>$val)
{
$student_id=$val['student_id'];
$phone=$val['phone_number'];
$status=$val['status'];
echo $student_id;
// find out last call successfully completed by the student
if($status==1)
{
$progress = getLastActivity($db,$student_id);
X
X
X
echo "done with initialize<br/>";
$server= "http://sample.com";
try {
$to = '+' . $phone;
echo $phone;
$questions_id_url='questions_id_0='.$questions_id[0].'&questions_id_1='.$questions_id[1].'&questions_id_2='.$questions_id[2];
$questions_file_url='questions_file_0='.$questions_file[0].'&questions_file_1='.$questions_file[1].'&questions_file_2='.$questions_file[2];
$url = $server.'/startCall.php?call_id='.$call_id.'&phone='.$phone.'&'.$questions_id_url.'&'.$questions_file_url.'&student_id='.$student_id.'&story='
.$story.'&story_id='.$story_id.'&call_number='.$call_number.'&question_number=0&count_english=0&count_hindi=0&insert_receivecall=0';
echo "here"."-----".$url;
$client->account->calls->create(
"+17864310795",
$to,
$url,
array(
'Method' => "GET",
'FallbackMethod' => "GET",
'StatusCallbackMethod' => "GET",
'Record' => "false",
));
} catch (Exception $e) {
// log error
}
}
}
?>
<Response>
<Reject reason="busy"/>
</Response>
I have tried everything, and was hoping I could spot the error

Twilio developer evangelist here.
I think your problem is that you're pushing out more than just XML within that script. You start by setting the content type to XML and echoing the XML declaration, but after that you start to echo what looks like debugging commands, which aren't valid XML, so the parser throws an error.
So, to start, I would comment out or remove anything that echos non XML content from your script.
Let me know if that helps.

Related

Getting a Parse error while executing a Twilio file to perform an action when a user calls the number [duplicate]

So I am trying to take an incoming SMS and based on what the SMS says make a call with a specific recording.
For example:
I have a door sensor with a modem that can send a text to my twilio # when the door is open or when the door is closed.
If Twilio receives "door open" text then twilio will call my cell phone and plays recording that says "door is open"
If Twilio receives "door closed" text then twilio will call my cell phone and plays recording that says "door is closed"
<?php
require_once('/home/protranx/public_html/twilio-php- latest/Services/Twilio.php');
$sid = "SID";
$token = "Token";
$client = new Services_Twilio($sid, $token);
$alert = $_REQUEST['body'];
$TwilioNumber = "+twilio #";
$to = "+my cell #";
$url1 = "http://protran.x10.mx/Oak1_armed_door_open.php";
$url2 = "http://protran.x10.mx/Oak1_disarmed_door_closed.php";
$string1 = "door open";
$string2 = "door closed";
if ($alert == $string1){
$call = $client->account->calls->create($TwilioNumber, $to, $url1);}
elseif ($alert == $string2){
$call = $client->account->calls->create($TwilioNumber, $to, $url2);}
echo $call->sid;
header('content-type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
</Response>
I keep getting this error:
Error: 12100 - Document parse failure
Any help would be greatly appreciated.
Thank you
Twilio evangelist here.
Hard to tell from your code, as it generally looks right.
One thing that occasionally trips me up is spaces being rendered before the start of the xml or between the xml declaration and the root element, so you might check for either of those that since those can be hard to catch.
For example, I'm not sure you need the newline that you have at the end of your xml declaration.
Hope that helps.

How do I take an SMS and make a call to alert someone based on what SMS says?

So I am trying to take an incoming SMS and based on what the SMS says make a call with a specific recording.
For example:
I have a door sensor with a modem that can send a text to my twilio # when the door is open or when the door is closed.
If Twilio receives "door open" text then twilio will call my cell phone and plays recording that says "door is open"
If Twilio receives "door closed" text then twilio will call my cell phone and plays recording that says "door is closed"
<?php
require_once('/home/protranx/public_html/twilio-php- latest/Services/Twilio.php');
$sid = "SID";
$token = "Token";
$client = new Services_Twilio($sid, $token);
$alert = $_REQUEST['body'];
$TwilioNumber = "+twilio #";
$to = "+my cell #";
$url1 = "http://protran.x10.mx/Oak1_armed_door_open.php";
$url2 = "http://protran.x10.mx/Oak1_disarmed_door_closed.php";
$string1 = "door open";
$string2 = "door closed";
if ($alert == $string1){
$call = $client->account->calls->create($TwilioNumber, $to, $url1);}
elseif ($alert == $string2){
$call = $client->account->calls->create($TwilioNumber, $to, $url2);}
echo $call->sid;
header('content-type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>
</Response>
I keep getting this error:
Error: 12100 - Document parse failure
Any help would be greatly appreciated.
Thank you
Twilio evangelist here.
Hard to tell from your code, as it generally looks right.
One thing that occasionally trips me up is spaces being rendered before the start of the xml or between the xml declaration and the root element, so you might check for either of those that since those can be hard to catch.
For example, I'm not sure you need the newline that you have at the end of your xml declaration.
Hope that helps.

Reading Web Service using PHP with GUID and Namespace

I am new to Web Services and am struggling to access/read the XML data using PHP (my website that will be using the data is in PHP).
The WSDL Url: http://services.mywheels.co.za/BWAVehicleStockService.svc?wsdl
I need to get access and read the Vehicle stock information but cant see to access anything.
the Array vehicle are stored under: http://services.mywheels.co.za/BWAVehicleStockService.svc?xsd=xsd2 .
i am using this code but it doesnt give my any data. I also have a GUID that i need to pass but have no idea how to add it to the header.
<?PHP
define('NEWLINE', "<br />\n");
// SOAP client
$wsdl = 'http://services.mywheels.co.za/BWAVehicleStockService.svc?wsdl';
$soapClient = new SoapClient($wsdl, array('cache_wsdl' => 0));
// SOAP call
$parameters->ArrayOfVehicle->Vehicle;
try
{
$result = $soapClient->GetVehicleStock($parameters);
}
catch (SoapFault $fault)
{
echo "Fault code: {$fault->faultcode}" . NEWLINE;
echo "Fault string: {$fault->faultstring}" . NEWLINE;
if ($soapClient != null)
{
$soapClient = null;
}
exit();
}
$soapClient = null;
echo "<pre>\n";
print_r($result);
echo "</pre>\n";
echo "Return value: {$result->GetDataResult}" . NEWLINE;
?>
if someone can help or point me in the right direction with this that would be great.
Thanks
You can add headers using __setSoapHeaders():
$h = new SoapHeader('http://tempuri.org/', 'Guid', '123');
$soapClient->__setSoapHeaders($h);
I had to read the WSDL itself to find out what namespace I should use; in this case they refer to Guid as tns:Guid and from the top you can read what URI is used to express that, hence http://tempuri.org.

php soapclient returns null but getPreviousResults has proper results

I've ran into trouble with SOAP, I've never had this issue before and can't find any information on line that helps me solve it.
The following code
$wsdl = "path/to/my/wsdl";
$client = new SoapClient($wsdl, array('trace' => true));
//$$textinput is passed in and is a very large string with rows in <item></item> tags
$soapInput = new SoapVar($textinput, XSD_ANYXML);
$res = $client->dataprofilingservice(array("contents" => $soapInput));
$response = $client->__getLastResponse();
var_dump($res);//outputs null
var_dump($response);//provides the proper response as I would expect.
I've tried passing params into the SoapClient constructor to define soap version but that didnt' help. I've also tried it with the trace param set to false and not present which as expected made $response null but $res was still null. I've tried the code on both a linux and windows install running Apache.
The function definition in the WSDL is (xxxx is for security reasons)
<portType name="xxxxServiceSoap">
<operation name="dataprofilingservice">
<input message="tns:dataprofilingserviceSoapIn"/>
<output message="tns:dataprofilingserviceSoapOut"/>
</operation>
</portType>
I have it working using the __getLastResponse() but its annoying me it will not work properly.
I've put together a small testing script, does anyone see any issues here. Do I need a structure for the return type?
//very simplifed dataset that would normally be
//read in from a CSV file of about 1mb
$soapInput = getSoapInput("asdf,qwer\r\nzzxvc,ewrwe\r\n23424,2113");
$wsdl = "path to wsdl";
try {
$client = new SoapClient($wsdl,array('trace' => true,'exceptions' => true));
} catch (SoapFault $fault) {
$error = 1;
var_dump($fault);
}
try {
$res = $client->dataprofilingservice(array("contents" => $soapInput));
$response = $client->__getLastResponse();
echo htmlentities($client->__getLastRequest());//proper request echoed
echo '<hr>';
var_dump($res);//null
echo "<hr>";
echo(htmlentities($response));//proper response echoed
} catch (SoapFault $fault) {
$error = 1;
var_dump($fault);
}
function getSoapInput($input){
$rows = array();
$userInputs = explode("\r\n", $input);
$userInputs = array_filter($userInputs);
//
$inputTemplate = " <contents>%s</contents>";
$rowTemplate = "<Item>%s</Item>";
//
$soapString = "";
foreach ($userInputs as $row) {
// sanitize
$row = htmlspecialchars(addslashes($row));
$xmlStr = sprintf($rowTemplate, $row);
$rows[] = $xmlStr;
}
$textinput = sprintf($inputTemplate, implode(PHP_EOL, $rows));
$soapInput = new SoapVar($textinput, XSD_ANYXML);
return $soapInput;
}
Ok after much digging it is related to relative namespaces, it appears that PHP doesn't handle them well within the WSDL or the SOAP Envelope. So since I don't have control of the SOAP Server I will continue to get the response via __getLastResponse();.
Hopefully this will save some people some time it was hard to find.
You are mixing things here. __getLastResponse() returns the bare XML string response from the server if you make use of the 'trace' => true option. That is for debugging only.
So regardless whether 'trace' => true or not, the method which you would like to call originally returns the same and that is totally normal. Setting tracing to on won't change the behaviour, it just offers an additional feature, the return value for __getLastResponse().
As the SoapClient does not throw any exception I'd say that your call is going okay and NULL is a valid return value.
You might want to provide the actual XML string and/or the WSDL defintion so that one could inspect if that's the case or not.

PHP Twilio App - Including SMS file breaks Foreach loop

I cant figure this out so I'm hoping you can lend a hand.
I am creating a twilio app, and I'm including this entire file in a foreach loop. But it keeps breaking my loop and wont continue after it runs.
It works great, but the foreach this is included inside of will not continue after it runs.
Any ideas?
Thanks,
Nick
<?php
//shorten the URL
$tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$ebay_url);
// Include the PHP TwilioRest library
require "twilio/twilio.php";
// Twilio REST API version
$ApiVersion = "2010-04-01";
// Set our AccountSid and AuthToken
$AccountSid = "removed";
$AuthToken = "removed";
// Instantiate a new Twilio Rest Client
$client = new TwilioRestClient($AccountSid, $AuthToken);
// make an associative array of server admins
$people = array(
"removed"=>"Nick",
//"4158675310"=>"Helen",
//"4158675311"=>"Virgil",
);
// Iterate over all our server admins
foreach ($people as $number => $name) {
// Send a new outgoinging SMS by POST'ing to the SMS resource */
// YYY-YYY-YYYY must be a Twilio validated phone number
$response = $client->request("/$ApiVersion/Accounts/$AccountSid/SMS/Messages",
"POST", array(
"To" => $number,
"From" => 'removed',
"Body" => 'Alert! '.$title.' found for '. $price. '. View the item here: '.$tinyurl,
));
if($response->IsError)
echo "Error: {$response->ErrorMessage}\n";
else
echo "Sent message to: {$response->ResponseXml->SMSMessage->To}\n";
}
?>
I think the problem is that you're doing a require inside the for loop. There are objects defined in that twilio library so the second time you require it, the classes get defined again and this throws an error.
If you have error_reporting(E_ALL) set then you'll see an exception to that effect in your output.
I would either change it to a require_once or move it out of the for loop.
I hope that helps.

Categories