When adding content to json file php error occurs - php

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.

Related

How to access final balance from blockchain

I have the following url:
https://blockchain.info/multiaddr?active=1AT4ES3ee1N6iBzzbdK8xvcAV3CBTRKcbS|1FHcYth4LRJMwNx2y8NR5DH7sYCiVzXs3Y&n=1
I want to access the final_balance from the output of the url.
I have the following code:
$value = file_get_contents($url);
$FinalBalance = $value["final_balance"];
var_dump($FinalBalance);
Error PHP Warning: Illegal string offset 'final_balance'
I also tried the following code:
$value = file_get_contents($url);
$json = json_decode($value);
var_dump($json);
$FinalBalance = $json["final_balance"];
var_dump($Final_Balance);
Error PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array
Your are near to finish that stuff but I will write down desired solution. Please have a look.
$url="https://blockchain.info/multiaddr?active=1AT4ES3ee1N6iBzzbdK8xvcAV3CBTRKcbS|1FHcYth4LRJMwNx2y8NR5DH7sYCiVzXs3Y&n=1";
$value = file_get_contents($url);
$FinalBalance = $value;
$data=json_decode($FinalBalance);
echo $data->wallet->final_balance;
echo $data->addresses[0]->final_balance;
echo $data->addresses[1]->final_balance;
exit;
You are going to access the inner object so you have to provide proper reference whether it is an array or an object.

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);

Trying to parse a json

After getting a json from Youtube API. I used this code to parse it:
$en = json_encode($json, true);
echo "<pre>";
print_r($en);
echo "</pre>";
here is the result:
{"items":[{"id":"UC-D8SQfw-J-lSWFSbyX6wRg"}]}
I made it clear with an online json parser here's how it looks:
{
"items":[
{
"id":"UC-D8SQfw-J-lSWFSbyX6wRg"
}
]
}
I want to get id value. I have tried $en->items->id but it says Notice: Trying to get property of non-object
how do I get the value of id ?
$en = json_encode($json, true);
$en_b = json_decode($en, true);
echo $en_b['items'][0]['id'];

how to check if simpleXML is null

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
}

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;

Categories