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);
Related
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.
This is my first attempt using Dropbox API and I'm just following the "Hello World" from PHP SDK. Upload methods is working fine, but download:
$app = new DropboxApp("...", "...", "...");
$dropbox = new Dropbox($app);
$file = $dropbox->download("/image.png", '/image.png');
Return this warning:
Warning: curl_exec(): Could not call the CURLOPT_WRITEFUNCTION in
/srv/www/website/public_html/dropbox/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php
on line 40
Fatal error: Uncaught RuntimeException: Unable to open /image.png
using mode w+: fopen(/image.png): failed to open stream: Permission
denied in
/srv/www/website/public_html/dropbox/vendor/guzzlehttp/psr7/src/functions.php:299
Stack trace: #0 [internal function]: GuzzleHttp\Psr7{closure}(2,
'fopen(/unifeal-...', '/srv/www/website/...', 307, Array) #1
/srv/www/website/public_html/dropbox/vendor/guzzlehttp/psr7/src/functions.php(307):
fopen('/image.p...', 'w+') #2
/srv/www/website/public_html/dropbox/vendor/guzzlehttp/psr7/src/LazyOpenStream.php(37):
GuzzleHttp\Psr7\try_fopen('/image.p...', 'w+') #3
/srv/www/website/public_html/dropbox/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php(31): GuzzleHttp\Psr7\LazyOpenStream->createStream() #4
/srv/www/website/public_html/dropbox/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php(136):
GuzzleHttp\Psr7\LazyOpenStream->__get('stream') #5
/srv/www/website/public_html/dropbox/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(380):
GuzzleHttp\Psr7\LazyOpenStream-> in
/srv/www/website/public_html/dropbox/vendor/guzzlehttp/psr7/src/functions.php
on line 299
I'm testing using Vagrant.
UPDATE
I can confirm that is not a permission issue because download works using this script:
$file = $dropbox->download("/image.png");
$contents = $file->getContents();
file_put_contents(__DIR__ . "/image.png", $contents);
$metadata = $file->getMetadata();
But not using the recommended way.
My code should convert "defindex" from array_inv into "item_name" from array_schema:
<?php
$apikey = "X";
$steamid = $steamprofile['steamid'];
$url_inv = "http://api.steampowered.com/IEconItems_730/GetPlayerItems/v0001/?language=en?key=". $apikey . "&steamid=" . $steamid . "&format=json";
$url_schema = "http://git.optf2.com/schema-tracking/plain/Counter%20Strike%20Global%20Offensive%20Schema?h=counterstrikeglobaloffensive";
$array_inv_raw = file_get_contents($url_inv);
$array_schema_raw = file_get_contents($url_schema);
$array_inv = json_decode($array_inv_raw,true);
$array_schema = json_decode($array_schema_raw,true);
foreach($array_inv['result']['items'] as $item){
foreach($array_schema['result']['items'] as $schemaItem){
if($item['defindex'] == $schemaItem['defindex']){
echo $schemaItem['item_name'].'<br />';
break;
}
}
}
?>
But it's resulting in these errors:
Warning:
file_get_contents(http://api.steampowered.com/IEconItems_730/GetPlayerItems/v0001/?language=en?key=x&steamid=76561198037897388&format=json):
failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in
/home/kartm/public_html/scripts/inv.php on line 6
Warning: Invalid argument supplied for foreach() in
/home/kartm/public_html/scripts/inv.php on line 12
The urls:
array_inv
array_schema
I can't find any mistakes. Can you tell me what's wrong with this code?
These errors were caused by a typo in a url:
http://api.steampowered.com/IEconItems_730/GetPlayerItems/v0001/?language=en?key=x&steamid=76561198037897388&format=json
It should have been & key=x instead of ?key=x.
file_get_contents couldn't fetch the url, thus the foreach had an invalid, empty argument.
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
}
I'm trying to get latitude and longtitude from google map by giving address. But it's giving error. When I directly copy url to browser url bar. it's giving correct result. If anybody know the answer.
Here is my code.
<?php
$key = '[AIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0]';
$opt = array (
'address' => urlencode('Kolkata,India, ON') ,
'output' => 'xml'
);
$url = 'http://maps.google.com/maps/geo?q='.$opt['address'].'&output='.$opt['output'].'&oe=utf8&key='.$key;
$dom = new DOMDocument();
$dom->load($url);
$xpath = new DomXPath($dom);
$xpath->registerNamespace('ge', 'http://earth.google.com/kml/2.0');
$statusCode = $xpath->query('//ge:Status/ge:code');
if ($statusCode->item(0)->nodeValue == '200') {
$pointStr = $xpath->query('//ge:coordinates');
$point = explode(",", $pointStr->item(0)->nodeValue);
$lat = $point[1];
$lon = $point[0];
echo '<pre>';
echo 'Lat: '.$lat.', Lon: '.$lon;
echo '</pre>';
}
?>
Following error has occured:
Warning: DOMDocument::load(http://maps.google.com/maps/geo? q=Kolkata%252CIndia%252C%2BON&output=xml&oe=utf8&key=%5BAIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0%5D) [domdocument.load]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\xampp\htdocs\draw\draw.php on line 19
Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "http://maps.google.com/maps/geo?q=Kolkata%252CIndia%252C%2BON&output=xml&oe=utf8&key=%5BAIzaSyAoPgQlfKsBKQcBGB01cl8KmiPee3SmpU0%5D" in C:\xampp\htdocs\draw\draw.php on line 19
Notice: Trying to get property of non-object in C:\xampp\htdocs\draw\draw.php on line 26
DOMDocument::load() requires allow_url_fopen to be true.
Check your php.ini-settings and switch it to 1.
See also:
http://php.net/filesystem.configuration.php#ini.allow-url-fopen
What would cause DOMDocument.load to fail loading XML from a URL that is accessible?