how to check if simpleXML is null - php

So, I build a script which contains multi curl to verify the XML and extrac $xml->loc from more urls but my script crash(stop) when he found anything else which is not a xml file
...multi curl code...
if($httpcode>=200 && $httpcode<=300) {
$xml = new SimpleXMLElement($data);
if($xml !== NULL) {
foreach ($xml->url as $url_list) {
$url = $url_list->loc;
$newurls[] = $url;
}
}
}
If i put 5 valid xml urls it works but if I put 100 link and one of them is not a XML file the script stops.
ERROR:
[root#test ~]# php a z2
PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /root/a:160
Stack trace:
#0 /root/a(160): SimpleXMLElement->__construct('\r\n<!DOCTYPE htm...')
#1 /root/a(65): mycurl_done('http://southpas...', '\r\n<!DOCTYPE htm...', Resource id #36)
#2 /root/a(175): ThreadsLoop()
#3 {main}
thrown in /root/a on line 160
[root#test ~]#
Seems like my script try to extract information from a html file because if the file don't exist it will redirect me to homepage(I guess)...
What options do I have to make to continue if the SimpleHTMLElement can't parse my $data variable which is the entire source code from a XML file?

You can use a try catch block to handle the exception.
try {
$xml = new SimpleXMLElement($data);
//XML is valid
...
} catch(Exception $e) {
//XML is invalid
}

Related

When adding content to json file php error occurs

I'm learning php and started following a youtube video for a project.
When i accept contents from my json file and code it to add new contents to it, an error occurs.
Error-
Warning: Undefined variable $json_encode in /Users/montekkundan/Downloads/coding/php/newtodo.php on line 16
Fatal error: Uncaught Error: Value of type null is not callable in /Users/montekkundan/Downloads/coding/php/newtodo.php:16 Stack trace: #0 {main} thrown in /Users/montekkundan/Downloads/coding/php/newtodo.php on line 16
php code-
<?php
// echo "<pre>";
// var_dump($_POST);
// echo "</pre>";
$todoname = $_POST['todoname'] ?? "";
$todoname = trim($todoname);
if($todoname) {
$json = file_get_contents('todo.json');
$jsonArray = json_decode($json, true);
$jsonArray[$todoname] = ['completed' => false];
// echo "<pre>";
// var_dump($jsonArray);
// echo "</pre>";
file_put_contents('todo.json', $json_encode($jsonArray, JSON_PRETTY_PRINT)) ;
}
?>
Try to change
file_put_contents('todo.json', $json_encode($jsonArray, JSON_PRETTY_PRINT));
to file_put_contents('todo.json', json_encode($jsonArray, JSON_PRETTY_PRINT));
that's because you are trying to call json_encode variable, json_encode is not a variable.

php foreach loop with urls from file

I am trying to the status of urls which are stored in a text file
in my code i have:
$filestatus = file("urlsmartins_status.txt");
foreach ($filestatus as $filestate){
$filestatusurl = (file_get_contents("$filestate"));
$filestatusurlxml = new SimpleXMLElement ($filestatusurl);
print_r ($filestatusurlxml);
}
in the urlsmartin_status.txt i have 5 urls written
http://172.27.73.5:8080/api/service/
http://172.27.73.6:8080/api/service/
http://172.27.73.7:8080/api/service/
http://172.27.73.8:8080/api/service/
But when i execute the code i have the following result
PHP Warning: file_get_contents(http://172.27.73.5:8080/api/service/
): failed to open stream: HTTP request failed! HTTP/1.1 404 OK
PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in ...
Stack trace:
#0 /opt/rh/httpd24/root/var/www/html/pub/martin.php(56): SimpleXMLElement->__construct('')
#1 {main}
thrown in /opt/rh/httpd24/root/var/www/html/pub/martin.php on line 56
What am i missing here?
Thanks
the problem here is that the lines in your file are not "XML", hence SimpleXMLElement cannot be instantiated.
I get the same error like this:
I managed to fix it via
$filedata = file_get_contents('urlsmartins_status.txt');
$urls = explode("\n", trim($filedata));
foreach($urls as $key => $url) {
$filestatusurl = file_get_contents("$url");
$filestatusurlxml = new SimpleXMLElement ($filestatusurl);
print_r ($filestatusurlxml);

Debug SOAP call in PHP: An exception has been raised as a result of client data

I am working with the UPS api and am having a difficult time debugging. I am getting the following stack trace:
Details
Type: SoapFault
Message: An exception has been raised as a result of client data.
File: /Users/shawn/Documents/work/sites/Wingspan/kaleco/lib/SixString/Utilities/Ups.php
Line: 161
Trace
#0 /Users/shawn/Documents/work/sites/Wingspan/kaleco/lib/SixString/Utilities/Ups.php(161): SoapClient->__soapCall('ProcessShipment', Array)
#1 /Users/shawn/Documents/work/sites/Wingspan/kaleco/routes/ups.php(14): SixString\Utilities\Ups->getShipment()
#2 [internal function]: {closure}()
#3 /Users/shawn/Documents/work/sites/Wingspan/kaleco/vendor/slim/slim/Slim/Router.php(172): call_user_func_array(Object(Closure), Array)
#4 /Users/shawn/Documents/work/sites/Wingspan/kaleco/vendor/slim/slim/Slim/Slim.php(1222): Slim\Router->dispatch(Object(Slim\Route))
#5 /Users/shawn/Documents/work/sites/Wingspan/kaleco/vendor/slim/slim/Slim/Middleware/Flash.php(86): Slim\Slim->call()
#6 /Users/shawn/Documents/work/sites/Wingspan/kaleco/vendor/slim/slim/Slim/Middleware/MethodOverride.php(94): Slim\Middleware\Flash->call()
#7 /Users/shawn/Documents/work/sites/Wingspan/kaleco/vendor/slim/slim/Slim/Middleware/SessionCookie.php(116): Slim\Middleware\MethodOverride->call()
#8 /Users/shawn/Documents/work/sites/Wingspan/kaleco/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php(67): Slim\Middleware\SessionCookie->call()
#9 /Users/shawn/Documents/work/sites/Wingspan/kaleco/vendor/slim/slim/Slim/Slim.php(1174): Slim\Middleware\PrettyExceptions->call()
#10 /Users/shawn/Documents/work/sites/Wingspan/kaleco/public/index.php(6): Slim\Slim->run()
#11 {main}
Here is the block of code:
try{
$mode = array('soap_version' => 'SOAP_1_1', 'trace' => 1,'exceptions' => true );
$client = new \SoapClient($wsdl , $mode);
$client->__setLocation($endpointurl);
$header = new \SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$this->upss);
$client->__setSoapHeaders($header);
if(strcmp($operation,"ProcessShipment") == 0 ) {
$resp = $client->__soapCall('ProcessShipment',array($this->processShipment()));
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//print_r($client->__getLastRequest());
}
else if (strcmp($operation , "ProcessShipConfirm") == 0) {
$resp = $client->__soapCall('ProcessShipConfirm',array($this->processShipConfirm()));
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
}
else {
$resp = $client->__soapCall('ProcessShipeAccept',array($this->processShipAccept()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
echo "<pre>";
print_r($resp);
echo "</pre>";
}
}
catch(Exception $ex){
print_r ($ex);
}
Line 161 is in the above code, this is the actual line:
$resp = $client->__soapCall('ProcessShipConfirm',array($this->processShipConfirm()));
I am looking for a way to debug this. It does not appear to be reaching the catch block and I cannot seem to determine the cause of the exception.
Try to catch exception with SoapFault and print its detail property.
try {
$response = $client->$call( $params );
} catch (\SoapFault $fault) {
//trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
var_dump($fault->faultcode);
var_dump($fault->faultstring);
var_dump($fault->detail);
die('Errore chiamata webservice UPS');
}
refer to: http://php.net/manual/en/function.is-soap-fault.php
I don't know the nuances of exception handling in PHP, but Soap exceptions are squirrely little buggers in C# as well. In Visual Studio's debugger, you can get at the details of unhandled exceptions right in the IDE. If you have an option to do this, look for the exception's "detail" XML Element, as this will contain the web service's message telling you what was borked with your request.
As for actually trapping the exception, there's an old but good article by #Jeff Atwood that — though written for (gasp) VB.NET — might still provide some insight into what makes Soap exceptions so, er... slippery: Coding Horror | Throwing better SOAP exceptions
NOTE: For what it's worth, UPS gives this error for bad tracking numbers. Use a good (valid) tracking number and it corrected my issue.
UPS gives this error also for bad ShipFrom/CountryCode or ShipTo/CountryCode in Rates API. e.g. germany can't be rated. This can't found in the UPS dev docs.

function php fwrite give a message error

Using my webservice I would like to save in a XML file the response that it display to me, but when I'm trying to save this data it displays mze an error:
here is the error I get:
Catchable fatal error: Object of class stdClass could not be converted to string in C:\wamp\www\NEOGETCASH\GESTIONNAIRE\DOSSIERS\creditsafe.php on line 13
the code I'm using is there; but I don't know I know that the response is as XML, but id doesn't save in the file I wanted I don't know why, just because it is not a varchar.
<?php
$wsdl = "https://www.creditsafe.fr/getdata/service/CSFRServices.asmx?WSDL";
$client = new SoapClient($wsdl);
$debiteur_siret = "<xmlrequest><header><username>demo</username><password>**********</password><operation>getcompanyinformation</operation><language>FR</language><country>FR</country><chargereference></chargereference></header><body><package>standard</package><companynumber>40859907400049</companynumber></body>
</xmlrequest> " ;
$o = new stdClass();
$o->requestXmlStr = $debiteur_siret;
$fichier =
//header('Content-Type: text/xml');
$texte=$client->GetData($o);
echo $texte;
$fp = fopen("tmp/".$_GET['n_doss'].".xml", "w+");
//fwrite($fp, $texte);
fclose($fp);
?>
The message comes from the lines:
$texte=$client->GetData($o);
echo $texte;
GetData does not return a string, but a stdClass instead, which can not be converted to a string. var_dump($texte) to see what it returns, and echo the appropriate property of the stdClass.
EDIT: I've looked up the WDSL and checked; the GetData() function returns a GetDataResponse, which seems to contain a property GetDataResult (a string). So the following should work:
$texte=$client->GetData($o);
echo $texte->GetDataResult;

YouTube PHP API - Zend_Gdata_App_HttpException

I've got a working website, which uses youtube api. Everything was fine but today I noticed I get error while using this api:
Fatal error: Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Expected response code 200, got 403 <?xml version='1.0' encoding='UTF-8'?><errors><error><domain>yt:quota</domain><code>too_many_recent_calls</code></error></errors>' in /root/public_html/grabandrun.com/public/ZendGdata/library/Zend/Gdata/App.php:700 Stack trace: #0 /root/public_html/grabandrun.com/public/ZendGdata/library/Zend/Gdata.php(221): Zend_Gdata_App->performHttpRequest('GET', 'http://gdata.yo...', Array, NULL, NULL, NULL) #1 /root/public_html/grabandrun.com/public/ZendGdata/library/Zend/Gdata/App.php(861): Zend_Gdata->performHttpRequest('GET', 'http://gdata.yo...', Array) #2 /root/public_html/grabandrun.com/public/ZendGdata/library/Zend/Gdata/App.php(754): Zend_Gdata_App->get('http://gdata.yo...', NULL) #3 /root/public_html/grabandrun.com/public/ZendGdata/library/Zend/Gdata/App.php(205): Zend_Gdata_App->importUrl('http://gdata.yo...', 'Zend_Gdata_YouT...', NULL) #4 /root/public_html/grabandrun.com/public/ZendGdata/library/Zend/Gdata.php( in /root/public_html/grabandrun.com/public/ZendGdata/library/Zend/Gdata/App.php on line 700
my code looks somehow like this:
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Uri_Http');
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setQuery($searchTerms);
$query->setStartIndex($index2);
$query->setMaxResults(10);
$query->setOrderBy($order);
$videoFeed = $yt->getVideoFeed($query);
foreach ($videoFeed as $videoEntry) {
$videoThumbnails = $videoEntry->mediaGroup->thumbnail[0]->url;
$title = $videoEntry->mediaGroup->title;
$vidId = $videoEntry->getVideoId();
$vidDescription = $videoEntry->mediaGroup->description;
$duration = $videoEntry->mediaGroup->duration->seconds;
$rating = round($videoEntry->rating->average,1)." out of 5";
echo "info...";
}
Funny thing is that it sometime works and sometime does not... I don't really know why, any help appreciated, thanks.
As stated in comments, I just had to limit the access and lower the calls. Thanks Slava.

Categories