How to convert the below mentioned xml data into json array in laravel - laravel-4

Find below the xml data:
<?xml version="1.0" encoding="utf-8"?> <interface-response> <Command>CHECK</Command> <APIType>API.NET</APIType> <Language>eng</Language> <ErrCount>1</ErrCount> <errors> <Err1>User not permitted from this IP address - 113.193.131.41. See http://enom.help/whitelist for details</Err1> </errors> <ResponseCount>1</ResponseCount> <responses> <response> <ResponseNumber>713254</ResponseNumber> <ResponseString>Policy error; unauthorized; user(s)</ResponseString> </response> </responses> <MinPeriod>1</MinPeriod> <MaxPeriod>10</MaxPeriod> <Server>sjl0vwapi08</Server> <Site>eNom</Site> <IsLockable>True</IsLockable> <IsRealTimeTLD>True</IsRealTimeTLD> <TimeDifference>+7.00</TimeDifference> <ExecTime>0.034</ExecTime> <Done>true</Done> <TrackingKey>5baa515b-8e29-4517-b879-05ae68e94f9a</TrackingKey> <RequestDateTime>5/9/2018 3:49:10 AM</RequestDateTime> <debug/> </interface-response>
I need to convert the above xml data to json array and pass it to view from the controller.
Find below the conrtroller code:
public function test()
{
$response = Curl::to('https://reseller.enom.com/interface.asp?command=check&sld=decksys&tld=info&responsetype=xml&uid=userid&pw=password')->get();
$data = simplexml_load_string($response);
$configdata = json_encode($data);
$value = json_decode($configdata, true);
return view('clientlayout.main.test', array('response' =>$response));
}
Find below the view code:
{{$response}}
The route is given below:
Route::get('/test','EnomController#test');
suggest a solution solve this and print the data in my view page.

Just do the following and that's all.
public function test()
{
$response = file_get_contents('your_xml_url');
$data = simplexml_load_string($response);
$configdata = json_encode($data);
return view('clientlayout.main.test', array('response' => $configdata ));
}

Related

ErrorException: Array to string conversion in file

I have a problem when updating the URLImg data when I use the PUT method, it throws the following error in Postman 'ErrorException: Array to string conversion in file' but if I use the POST method I have no problem uploading the urls of my images.
public function store(Request $request)
{
$values = $request->except('URLImg');
$data = $request->only('URLImg[]');
if($request->hasFile('URLImg')){
foreach($request->file("URLImg") as $image)
{
$name = Str::random(10).'.'.$image->getClientOriginalExtension();
$path = 'storage/img/';
$image->move($path, $name);
$data[] = $name;
$tramite = Tramite::create($values);
$tramite->URLImg = json_encode($data);
$tramite->save();
}
}else{
$tramite = Tramite::create($values);
$tramite->save();
}
return response()->json($tramite, 201);
public function update(Request $request, Tramite $tramite)
{
$data = $request->only('URLImg[]');
if($request->hasFile('URLImg')){
foreach($request->file("URLImg") as $image)
{
$name = Str::random(10).'.'.$image->getClientOriginalExtension();
$path = 'storage/img/';
$image->move($path, $name);
$data[] = $name;
$tramite->URLImg = json_encode($data);
$tramite->save();
}
}
return response()->json($tramite, 201);
}
Postman Config
Postman Config
Yes, it is almost the same code but I only need to update the URLImg field
Want to use a PUT or PATCH request for form containing file uploads - submit a POST request with method spoofing
<form action="/foo/bar" method="POST">
#method('PUT')
...
</form>
via any javascript framework like vue
let data = new FormData;
data.append("_method", "PUT")
axios.post("some/url", data)
Using _method and setting it to 'PUT' or 'PATCH' will allow to declare route as a PUT route and still use POST request to submit form data
$_FILES will not be populated on a PUT or PATCH request with multipart/form-data - PHP limitation

How do I loop over json data

I am using FlutterWave as my payment gateway, I want to loop through a transaction whenever a customer finish making payment and check for the chargeamount which the user paid. the return data is in json format. Here is my code.
public function callback(Request $request)
{
$resp = $request->resp;
$body = json_decode($resp, true);
$txRef = $body['data']['data']['txRef'];
$data = Rave::verifyTransaction($txRef);
dd($data);
return redirect()->route('success');
}
I want to loop and check for the chargedamount but I couldn't. Thanks for your help
Seems like you are dumping an object. I don't think you need a loop to access the data you need. According to your image dump, to access the chargedamount attribute:
dd($data->data->chargedamount);
The data name here repeats, perhaps $payload in this case, its a better name.
public function callback(Request $request)
{
$resp = $request->resp;
$body = json_decode($resp, true);
$txRef = $body['data']['data']['txRef'];
$payload = Rave::verifyTransaction($txRef);
dd($payload->data->chargedamount);
return redirect()->route('success');
}
Some clean up:
public function callback(Request $request)
{
$json = json_decode($request->resp);
$payload = Rave::verifyTransaction($json->data->data->txRef);
dd($payload->data->chargedamount);
return redirect()->route('success');
}
Again that data->data repeating stuff, but in this case, nothing we can do, its in the API.

How to insert into couchDB in laravel

How to insert the records to couchDB in laravel. i have done the retrieval part but now I want to do insert, update and delete .
My retrieval code is below.
class couchdbcontroller extends Controller
{
public function getdata()
{
$content =null;
try {
$client = new Client();
$apiRequest = $client->request('GET','http://localhost:5984/user/_design/userdesign/_view/user-view?limit=20&reduce=false');
$code = $apiRequest->getBody()->getContents();
} catch (RequestException $re) {
//For handling exception
return $re->error;
}
return $code;
//return response()->json($code);
}
}
Inserting code below:
public function guzzle_insert_doc()
{
$client = new Client();
$res = $client->request('PUT', 'http://localhost:5984/login/new_doc',[
'uname' => 'admin',
'password' => 'admin123',
]);
//return $res;
}
Error: Client error: PUT http://localhost:5984/login/new_doc resulted in a 400 Bad Request response:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}
From my google search, you could do something like this :
<?php
$client = new Client();
$doc = ['title'=>'This is a new doc'];
$res = $client->request('PUT', 'http://localhost:5984/db/new_doc',['json' => $doc]);
I assume you're using Guzzle (If I am wrong, tell us what your are using)
I didn't test my code since I don't have time to setup a laravel project with Guzzle. See documentation for further help.

How to use callback url in twilio codeigniter

$data = array(
'From' => $from,
'To' => $to,
'Url' => site_url('dashboard/call2')
);
// make call request to Twilio
try{
$twilio = new TwilioRestClient($account_sid, $account_token);
$result = $twilio->request('2010-04-01/Accounts/'. $account_sid .'/Calls',
'POST',
$data
);
pr($result);
}
catch (Exception $e){
pr($e);
}
public function call2() {
$this->load->view('response');
}
here response is a xml file in views. response.xml has to call as callback url.
but it is showing error:
XML Parsing Error: XML or text declaration not at start of entity
Location: http://www.website.com/index.php/dashboard/call2
Line Number 1, Column 5: <?xml version="1.0" encoding="UTF-8"?>
It looks like there is leading whitespace before the <?xml declaration. This will cause the document to fail to be parsed.
Check if there is whitespace outside of your PHP tags, including possibly after a closing ?> tag. This will show up in the XML output.

xpath php attributes not working?

Getting this error
Call to a member function attributes() on a non-object
I have found multiple answers to this on SO, but none of them seem to solve my problem?
Here is the XML:
<Routes>
<Route type="source" name="incoming">
</Route>
<Routes>
Here is the PHP:
$doc = new SimpleXMLElement('routingConfig.xml', null, true);
class traverseXML {
function getData() {
global $doc;
$routeCount = count($doc -> xpath("Route")); //this value returns correctly
$routeArr = array();
for ($i = 1; $i <= $routeCount; $i++) {
$name = $doc -> Route[$i] -> attributes() -> name;
array_push($routeArr, $name);
}
return $routeArr;
}
}
$traverseXML = new traverseXML;
var_dump($traverseXML -> getData());
I understand what the error means, but how is it a non-object? How do I return the name attribute of Routes/Route[1] ?
Your $doc is <Routes>. Trying to get ->Routes from it is trying to get
<Routes>
<Routes>
You need to do $doc->Route[$i]. Errors like this are less frequent when you name your variable after the document root:
$Routes = new SimpleXMLElement('routingConfig.xml', null, true);
Also, your XML is invalid. The Routes element is not closed.
In addition, you don't need the XPath. SimpleXML is traversable, so you can foreach over all the routes by doing
foreach ($Routes->Route as $route) {
And attributes() returns an array, so you cannot chain ->name off it but must access it with square brackets. But it's not necessary to use attributes() anyway because you can get attributes from SimpleXmlElements directly via square brackets, e.g.
echo $route['name'];
Here is an example that will print "incoming":
$xml = <<< XML
<Routes>
<Route type="source" name="incoming"/>
</Routes>
XML;
$routes = simplexml_load_string($xml);
foreach ($routes->Route as $route) {
echo $route['name'];
}
demo
If you want to do it with XPath, you can collect all the attributes in an array like this:
$routeNames = array_map('strval', $Routes->xpath('/Routes/Route/#name'));
Yes, it's just that one line :)
As for your class:
Don't use global. Forget it exists. If you want to have a class, inject the dependency, e.g. do
class Routes
{
private $routes;
public function __construct(SimpleXmlElement $routes)
{
$this->routes = $routes;
}
public function getRouteNames()
{
return array_map('strval', $this->routes->xpath('/Routes/Route/#name'));
}
}
$routes = new Routes(simplexml_load_string($xml));
print_r($routes->getRouteNames());
demo

Resources