I'm working on creating a class for xml parsing, and need to use this method from PHP called xml_parse.
It has 3 parameters like so:
int xml_parse ( resource $parser , string $data [, bool $is_final = false ] )
According to the PHP manual is_final it means whether its the last piece of data sent in this parse, but what does this mean? does this something have to do with resource $parser? as far as I'm aware this function does not allow an input stream of data, thus my confusion.
Someone please explain what it does
is_final means that if you are parsing the last line of your $data you must set this parameter to true.
in addition there is a note in the Doc :
Entity errors are reported at the end of the parse. And will only show if the "end" parameter is TRUE
See the sample below from w3schools
<?php
$parser=xml_parser_create();
function char($parser,$data)
{
echo $data;
}
xml_set_character_data_handler($parser,"char");
$fp=fopen("test.xml","r");
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
xml_parser_free($parser);
?>
Related
I have a PHP class file, I need to use the __ CLASS __ , __ LINE __ constants in lots of place. I don't want to write these tow constants in every place so, I have create the method called log_suffix() in my class file and using that method.
function detail(){
$leave_groups = LeaveGroup::get_leave_group_details($this->company_id, 1, true);
if($this->debug){
print_r($leave_groups->toArray());
}
if($leave_groups->count() === 0){
Log::error("log: " . $this->log_suffix() );// Line 39
return false;
}
return $leave_groups;
}
function log_suffix(){
return "$this->company_code | $this->company_name \t on File: ". _CLASS_. "\t". __LINE__ ; // Line no 51
}
the problem is, It is printing the line no 51 ( line constant written line ).
Is it possible to get the compile time line no that is 39 according to the shared image.
I know that with a try catch exception we can do this ( get the file and line no ).
rather than that is there any other way to sort out this issue.
here is online editor link
As per magic constants documentation, __LINE__ contains the "The current line number of the file.", that is the line where it is used. Therefore, looking at the example posted, in the log_suffix() function it will always print 51, wherever this function is called.
You could pass __LINE__ as a parameter of this function when it is called, , because it will hold the line number where the function is actually called, but this is what you want to avoid.
Another possibility is to use debug_backtrace() function in log_suffix(), with parameter limit = 1. It will return an array with one key, whose value is an array. The 'line' key holds the line of the previous calling scope.
A quick example:
$debugTrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 1);
$callerLine = $debugTrace[0]['line'];
I get the following error:
Catchable fatal error: Argument 1 passed to CorenlpAdapter::getOutput() must be an instance of string, string given, called in /Library/WebServer/Documents/website/php-stanford-corenlp-adapter/index.php on line 22 and defined in /Library/WebServer/Documents/website/php-stanford-corenlp-adapter/src/CoreNLP/CorenlpAdapter.php on line 95
index.php 21 and 22 contain:
$text1 = 'I will meet Mary in New York at 10pm';
$coreNLP->getOutput($text1);
corenlpAdapter.php lines 95 and onwards contain:
public function getOutput(string $text){
if(ONLINE_API){
// run the text through the public API
$this->getServerOutputOnline($text);
} else{
// run the text through Java CoreNLP
$this->getServerOutput($text);
}
// cache result
$this->serverMemory[] = $this->serverOutput;
if(empty($this->serverOutput)){
echo '** ERROR: No output from the CoreNLP Server **<br />
- Check if the CoreNLP server is running. Start the CoreNLP server if necessary<br />
- Check if the port you are using (probably port 9000) is not blocked by another program<br />';
die;
}
/**
* create trees
*/
$sentences = $this->serverOutput['sentences'];
foreach($this->serverOutput['sentences'] as $sentence){
$tree = $this->getTreeWithTokens($sentence); // gets one tree
$this->trees[] = $tree; // collect all trees
}
/**
* add OpenIE data
*/
$this->addOpenIE();
// to get the trees just call $coreNLP->trees in the main program
return;
}
Why exactly am I getting this error when text1 is a string?
I am the original author of this class. As you can see, the function getOutput looks like this:
public function getOutput(string $text){
...
}
Change that to:
public function getOutput($text){
...
}
The function tries to enforce that the input is string. The original code should work. However, it seems that in your case, PHP thinks "string" is not actually a string. Maybe the coding environment (the IDE) you are using uses the wrong character set? Or maybe you copy-pasted the code from HTML into the IDE or something like that. Thus whilst it says "string" on the screen, it's not actually a string to PHP.
If you are sure the input is a string, you can safely change the code like above. The class should then work normally.
public function getOutput($text){
.
.
.
}
I have a customer support system which creates emails when an email is received. I used to postfix and a special configuration to get a hold of the emails to add extra features.
For example I want to include attachments that were sent from an email. The system doesnt do this , but creates an email with the subject , so I can include the attachments by matching the subjects.
I used ImapMailBox.php to read through the email contents.
It all works fine but I am getting an issue fetching the last email, so I am gettign contents from any other email with the same subject , so I need to fetch the latest email.
$mailboxP = new ImapMailbox('{127.0.0.1:143/novalidate-cert}',POSTFIX_EMAIL,POSTFIX_PASSWORD,ATTACHMENT_DIR, 'utf-8');
foreach($mailbox->searchMails('ALL') as $mailId)
$mail = $mailbox->getMail($mailId);
$mailx=(array)$mail;
$att=$mailx['attachments'];
I have tried using usort to the object $mail , with a function like this
function
mysort($a,$b) {
return strtotime($a->date)-strtotime($b->date);
}
and to the array with a function like this
function mysort($a,$b) {
return strtotime($a['date'])-strtotime($b['date']);
}
I have also tried using imap_sort to $mail and $mailx , but none of this works.
errors I am getting
imap_sort() expects parameter 1 to be resource, array given
imap_sort() expects parameter 1 to be resource, object given
usort() expects parameter 1 to be array, object given
when passing an array I get undefined index date but it defined ..
Can anyone please be kind enough to point me in the right direction.
You can add a function like this on ImapMailbox.php :
public function searchMailsSorted($imapCriteria = 'ALL') {
$this->checkConnection();
$mailsIds =imap_sort($this->mbox,SORTDATE,1,SE_UID,$imapCriteria,$this->serverEncoding);
return $mailsIds ? $mailsIds : array();
}
And then use it in your code like this:
foreach($mailbox->searchMailsSorted('ALL') as $mailId)
{
///insert code here
}
The easiest way is to use Php rsort() function.
<?php
$emailId = rsort($mailbox->searchMails('ALL');
?>
I hope the title isn't too confusing, I'll try to explain better below.
Suppose I have a function in a separate file, functions.php:
function divide($num1, $num2) {
if ($num1 == 0 || $num2 == 0) {
trigger_error("Cannot divide by 0", E_USER_ERROR);
} else {
return ($num1 / $num2);
}
}
And another file that calls it:
include "functions.php";
echo divide(10, 0);
My error is
Fatal error: Cannot divide by 0 in
C:\Users\Derek\Desktop\projects\functions.php on line 5
My question is, how do I make that error instead point to the location of the error in the main code, so I instead get:
Fatal error: Cannot divide by 0 in
C:\Users\Derek\Desktop\projects\main.php on line 3
The particular reason I want this is because I have a function called load_class that simply finds a PHP file and instantiates the object inside, but if given an incorrect file name, it reports an error from inside load_class, which is technically true, but it's not particularly helpful if I don't remember where I called load_class in the first place. I would like the error to point to the file that called load_class incorrectly.
Also, I would like to write a function error() (something like below) that when given a message as a parameter would throw more "meaningful" error messages, but when done that way, the error always says it comes from error(), not from where the error actually came from!
For example, in an error.php:
/**
* error()
*
* Throws an error of a certain type
*
* #param string $type The type of error. "Fatal", "warning," or "notice"
* #param string $message A description of the error
* #return void
*/
function error($type, $message) {
switch (strtolower($type)) {
case 'fatal':
trigger_error($message, E_USER_ERROR);
break;
case 'notice':
trigger_error($message, E_USER_NOTICE);
default:
trigger_error($message, E_USER_WARNING);
break;
}
}
And in an index.php
error("fatal", "A sample warning!");
My error given is:
Fatal error: A sample warning! in
C:\Users\Derek\Desktop\projects\synthesis\sys\Error.php on line 45
But the error didn't occur in error.php, it happened in index.php! How can I make it show where it really came from?
The debug_backtrace function allows you to obtain the stacktrace as an array. You can pick the original location from there.
Next to that you need to slip into the error message to make this look-alike. Example:
function divide($num1, $num2) {
if ($num1 == 0 || $num2 == 0) {
trigger_error_original("Cannot divide by 0", E_USER_ERROR);
} else {
return ($num1 / $num2);
}
}
function trigger_error_original($message, $type) {
$trace = debug_backtrace(FALSE);
list($location) = array_slice($trace, 1, 1) + array('file' => 'unknown', 'line' => 'unknown');
$message .= sprintf(" in %s on line %d\nTriggered", $location['file'], $location['line']);
trigger_error($message, $type);
}
divide(1, 0);
The error message than shows something like:
> php test-pad.php
Fatal error: Cannot divide by 0 in test-pad.php on line 18
Triggered in test-pad.php on line 15
The downside of this is, that you need to change your code to have this "feature". If you need this for debugging your own code, it's much better that you enable backtraces in your logs. The Xdebug extension does this for you, or you can write your own error handler that takes care of that.
See as well the related question Caller function in PHP 5?. I used array_slice so that you could create an additional parameter to define the number of steps you want to go "up" in the backtrace.
Use debug_backtrace(), and debug_print_backtrace() for a full call stack. These are especially effective when using Xdebug, which will override the function to colorize the output.
I have this same problem...
#1: while 10/0 = ERROR, 0/10 = 0 is perfectly legal, you shouldn't have an exception for that.
#2: when you include a file, it effectively becomes part of this new file, so perhaps you might have to toy a little bit with things like __FILE__ and see if you can make it point it to the file before it gets included in the other file..
You can use xdebug - it will show you the stacktrace or you can register your own error handndler and display the stacktrace. Just check the example in php.net for set_error_handler().
Maybe exceptions are better to use in your case. You get the full stacktrace and can locate where the function was called without relying on some tricky code :)
// Set username and password
$ih_soap_user= $this->config->item('interUser');
$ih_soap_pass=$this->config->item('interPass');
//echo $ih_soap_user.':P:'.$ih_soap_pass;
// Set soap namespace
$ih_soap_ns = 'http://www.interhome.com/webservice';
// Create new instance of SoapClient with the interhome web service URL
$client = new
SoapClient($this->config->item('interSoap'),array('trace'=>'1'));
// Create new soap header and set username and password
$header = new SoapHeader($ih_soap_ns,
'ServiceAuthHeader',
array('Username' => $ih_soap_user,'Password' =>
$ih_soap_pass),
true
);
// Prepare p// Prepare parameters
$params = array('inputValue' =>array(
'Page'=>$page,
'PageSize'=>'10',
'OrderDirection'=>'Ascending',//Descending
'OrderBy'=>'Price',//Favorite,Place
'LanguageCode'=>'EN',
'CurrencyCode'=>'EUR',
'CountryCode'=>trim($ajaxSearchCountryCode),
'RegionCode'=>trim($ajaxSearchRegionCode),
'PlaceCode'=>$ajaxSearchPlaceCode,
'CheckIn'=> $ajaxSearchCheckinDate,
'Duration'=>'7',
'ThemeFilter'=>$ajaxSearchTheme,
'HouseApartmentType'=>array('House'=>'House'),
'SpecialOffer'=>'AnySpecialOffer',
'PaxMin'=>'1',
'PaxMax'=>'',
'RoomsMin'=>'1',
'RoomsMax'=>'',
) );
try{
$result = $client->__soapCall("Search",array('parameters'=> $params),null,$header);
Hi guys..Any Idea why this call when I pass any not empty array, as for example ,as I made for 'HouseApartmentType', returns this error
A PHP Error was encountered
Severity: Notice Message:
Array to string conversion
Filename:
controllers/houses.php Line
Number: 269
And when it's only empty array or a string the soap call function is working... I need to pass array of options to one parameter....
LINE 269 is
$result = $client->__soapCall("Search",array('parameters'=> $params),null,$header);
This is probably solved already, but I also had problems with this and I thought I should post here when I finally found the solution. (The solution is not nusoap, it throws the same error.)
The error only seems to come from the soapCall call generation, it really is the Web Service that causes it. When you run __soapCall, it first asks the server which datatypes the parameters should have and then tries to comply. So if you try to feed an array when the service expects a string, it will do the array to string conversion when the request is generated.
i think you should look at the manual how a soapcall work:
$params = array(
'Page'=>$page,
'PageSize'=>'10',
'OrderDirection'=>'Ascending',//Descending
'OrderBy'=>'Price',//Favorite,Place
'LanguageCode'=>'EN',
'CurrencyCode'=>'EUR',
'CountryCode'=>trim($ajaxSearchCountryCode),
'RegionCode'=>trim($ajaxSearchRegionCode),
'PlaceCode'=>$ajaxSearchPlaceCode,
'CheckIn'=> $ajaxSearchCheckinDate,
'Duration'=>'7',
'ThemeFilter'=>$ajaxSearchTheme,
'HouseApartmentType'=>'House', // changed to string instead of array
'SpecialOffer'=>'AnySpecialOffer',
'PaxMin'=>'1',
'PaxMax'=>'',
'RoomsMin'=>'1',
'RoomsMax'=>'' );
i simplified the array and you should test it and look if this is the kind of result you are looking for.
Also look for ordering errors like the example shown in php.net