I need to convert json format to xml using laravel.
I'm expecting output like following.
<MESSAGE>
<AUTHKEY>Your auth key</AUTHKEY>
<SENDER>SenderID</SENDER>
<ROUTE>Template</ROUTE>
<CAMPAIGN>campaign name</CAMPAIGN>
<COUNTRY>country code</COUNTRY>
<SMS TEXT="message1">
<ADDRESS TO="number1"></ADDRESS>
</SMS>
</MESSAGE>
The array I tried to convert is,
$TEXT="HI MANI";
$MESSAGE=array("AUTHKEY"=>"68252AGguI2SK45395d8f7",
"ROUTE"=>"4","CAMPAIGN"=>"TEST",
"SENDER"=>"OODOOP","SMS"=>array("TEXT"=>$TEXT,"ADDRESS"=>array("-TO"=>"8870300358")));
$json=array("MESSAGE"=>$MESSAGE);
$jsn=json_encode($json);
This xml output json to xml:
<?xml version="1.0" encoding="utf-8"?>
<xml>
<MESSAGE>
<AUTHKEY>68252AGguI2SK45395d8f7</AUTHKEY>
<ROUTE>4</ROUTE>
<CAMPAIGN>TEST</CAMPAIGN>
<SENDER>OODOOP</SENDER>
<SMS>
<TEXT>HI MANI</TEXT>
<ADDRESS><-TO>8870300358
</-TO>
</ADDRESS>
</SMS>
</MESSAGE>undefined</xml>
I got wrong output, tag mistake.
I know it is an old thread but i hope this can help anyone who seek support.
<?php
//build and array of the data you want to writ as XML
$xml_array = array ("message" => array(
"authkey"=> "68252AGguI2SK45395d8f7",
"route" => 4,
"campaign" => "test",
"sender" => "oooop",
"sms" => array (
"attribute" => "text:Hi Man",
"address" =>array (
"attribute" => "to:8870300358"
)
)
)
);
// create an XML object
$xmlobj = new SimpleXMLElement("<root></root>");
// a convert function
// this will take array in the above format and convert it in to XML Object
function convert($array, $xml){
foreach($array as $key=>$line){
if(!is_array($line)){
$data = $xml->addChild($key, $line);
}else{
$obj = $xml->addChild($key);
if(!empty($line['attribute'])){
$attr = explode(":",$line['attribute']);
$obj->addAttribute($attr[0],$attr[1]);
unset($line['attribute']);
}
convert($line, $obj);
}
}
return $xml;
}
$xmldoc =convert($xml_array,$xmlobj);
// text.xml is a blank file to write the data in it , you should create it first and give it WRITE permission
// in my case i just create it by and
print $xmldoc->asXML('test.xml');
print "<a href='test.xml'> XML file</a>";
:)
Related
In a Catalyst application, I need to generate JSON from DBIx::Class:Core objects.
Such a class definition looks like this:
use utf8;
package My::Schema::Book;
use strict;
use warnings;
use Moose;
use MooseX::NonMoose;
use MooseX::MarkAsMethods autoclean => 1;
extends 'DBIx::Class::Core';
__PACKAGE__->load_components("InflateColumn::DateTime");
__PACKAGE__->table("books");
__PACKAGE__->add_columns(
"id",
{
data_type => "uuid",
default_value => \"uuid_generate_v4()",
is_nullable => 0,
size => 16,
},
"title"
);
__PACKAGE__->set_primary_key("id");
__PACKAGE__->meta->make_immutable;
sub TO_JSON {
my $self = shift;
{book => {
id => $self->id,
title => $self->title,
}}
}
1;
After queriyng the books from database I do the encoding of the blessed objects:
$c->stash(books_rs => $c->model('My::Schema::Book'));
$c->stash(books => [$c->stash->{books_rs}->search(
{},
{order_by => 'title ASC'})]
);
$c->stash(json => $json->convert_blessed->encode($c->stash->{books}));
$c->forward('View::JSON');
The JSON output of the query is this:
{"json":"[{\"book\":{\"id\":\"ae355346-8e19-46ee-88ee-773ac30938a9\",\"title\":\"TITLE1\"}},{\"book\":{\"id\":\"9a20f526-d4cd-4e7d-a726-55e78bc3c0ac\",\"title\":\"TITLE2\"}},{\"book\":{\"title\":\"TITLE3\",\"id\":\"1ddb2d27-3ec6-46c1-a1a7-0b151fe44597\"}}]"}
The value of the json key and each particular book key got double quotes what can not be parsed by jQuery. It complains about format exception.
$json->convert_blessed->encode($c->stash->{books}) returns a string. It looks like View::JSON also encodes json.
Try to pass your data as is: $c->stash(json => $c->stash->{books});. You may also need to configure expose_stash and json_encoder_args to handle the right keys from your stash and correctly convert your objects.
See
https://metacpan.org/pod/Catalyst::View::JSON#CONFIG-VARIABLES
I have to post data as json object format in codeigniter. how can it make possible.
My model function looks like:
public function signAction()
{
$name=$this->input->post('name',TRUE);
$dob=$this->input->post('dob',TRUE);
$gender=$this->input->post('gender',TRUE);
$country=$this->input->post('country',TRUE);
$city=$this->input->post('city',TRUE);
$mobile=$this->input->post('mobile',TRUE);
$email=$this->input->post('email',TRUE);
$password=$this->input->post('password',TRUE);
$this->db->select("*");
$this->db->where('email',$email);
$this->db->or_where('mobile',$mobile);
$query = $this->db->get('dr_signup');
$value=$query->num_rows();
if($value==0)
{
$sql = "INSERT INTO dr_signup (name,dob,gender,country,city,mobile,email,password)
VALUES(".$this->db->escape($name).",".$this->db->escape($dob).",".$this->db->escape($gender).",".$this->db->escape($country).",
".$this->db->escape($city).",".$this->db->escape($mobile).",".$this->db->escape($email).",".$this->db->escape($password).")";
$value1=$this->db->query($sql);
$insert_id = $this->db->insert_id();
$details = array(
'status'=>'success',
'message'=>'registered sucessfully',
'id' => $insert_id ,
'name' => $name,
'dob'=>$dob,
'gender'=>$gender,
'country'=>$country,
'city'=>$city,
'mobile'=>$mobile,
'email'=>$email,
);
echo json_encode($details);
}
else
{
$detail = array(
'status'=>'unsuccess',
'message'=>'already registered',
);
echo json_encode($detail);
}
}
I have to post the data as json format. My json objects looks like:
{"name":"jon","dob":"1jan2015","gender":"male","country":"India","city":"Mumbai","mobile":"86064 70000","email":"sales#green.tech","password":"1234"}
I am new to this. How can it make possible. what all modification should I have to do in code. thanking in advance.
say for example you get the json in $this->input->post('json_string',true); you can use the code like this..
$jsonstring = $this->input->post('json_string');
$json_data = json_decode($jsonstring,true); //remove true if you need object or keep it for array
The $json_data will give you the key value of the posted json string like $json_data['name'] ...
You try just like this
return json_encode($details);
delete your code "echo json_encode($details)"
I think it's working
i have the following sql statement inside a function..
my $sth = $dbh->prepare(qq[SELECT device_uuid,device_name FROM ].DB_SCHEMA().qq[.user_device WHERE user_id = ?]);
$sth->execute($user_id) || die $dbh->errstr;
the results are being fetched using the following statement
while(my $data = $sth->fetchrow_arrayref()) {
}
my question is how can i create and return a json structure containing objects for every row being fetched?something like this
{
object1:{
"device_uuid1":"id1",
"device_name1":"name1"
},
object2:{
"device_uuid2":"id2",
"device_name2":"name2"
},
object3:{
"device_uuid3":"id3",
"device_name3":"name3"
}
}
the total number of json objects will be equal to the number of rows returned by the sql statement.
i have managed to build the structure like this
$VAR1 = [{"device_name":"device1","device_id":"device_id1"},{"device_name":"device2","device_id":"device_id2"}]
how can i iterate through the array refs and get "device_name" and "device_id" values?
For your needs, this library should work well. What you need to do is have a scalar variable defined as below and push the element for each iteration in while loop
my $json = JSON->new->utf8->space_after->encode({})
while(my $data = $sth->fetchrow_arrayref()) {
#Push new element here in $json using incr_parse method
#or using $json_text = $json->encode($perl_scalar)
}
Hope this helps you.
finally what i did was to create an array ref and push the fetched rows which are being returned as hash refs
my #device = ();
while(my $data = $sth->fetchrow_hashref()) {
push(#device, $data);
}
last i convert the #device array ref to json and return the outcome
return encode_json(\#device);
The statement handle method fetchall_arrayref() can return an array reference where each element in the referenced array is a hash reference containing details of one row in the resultset. This seems to me to be exactly the data structure that you want. So you can just call that method and pass the returned data structure to a JSON encoding function.
# Passing a hash ref to fetchall_arrayref() tells it to
# return each row as a hash reference.
my $json = encode_json($sth->fetchall_arrayref({});
Your sample JSON is incorrect - JSON is actually quite nicely represented by perl data structures - [] denotes array, {} denotes key-value (very similar to hash).
I would rather strongly suggest though, that what you've asked for is probably not what you want - you've seemingly gone for globally unique keys, which ... isn't good style when they're nested.
Why? well, so you can do things like this:
print $my_data{$_}->{'name'} for keys %my_data;
Far better to go for something like:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use JSON;
my %my_data = (
object1 => {
uuid => "id1",
name => "name1"
},
object2 => {
uuid => "id2",
name => "name2"
},
object3 => {
uuid => "id3",
name => "name3"
},
);
print Dumper \%my_data;
print to_json ( \%my_data, { 'pretty' => 1 } )."\n";
Now, that does assume your 'object1' is a unique key - if it isn't, you can instead do something like this - an array of anonymous hashes (for bonus points, it preserves ordering)
my #my_data = (
{ object1 => {
uuid => "id1",
name => "name1"
}
},
{ object2 => {
uuid => "id2",
name => "name2"
}
},
{ object3 => {
uuid => "id3",
name => "name3"
}
},
);
Now, how to take your example and extend it? Easy peasy really - assemble what you want to add to your structure in your loop, and insert it into the structure:
while(my $data = $sth->fetchrow_arrayref()) {
my $objectname = $data -> [0]; #assuming it's this element!
my $uuid = $data -> [1];
my $name = $data -> [2];
my $new_hash = { uuid => $uuid, name => $name };
$mydata{$objectname} = $new_hash;
}
I want to get some data from the URL above, I would like to get all of the torrent names under the search query.
http://kickass.to/usearch/grand%20theft%20auto%20v%20category:ps3/
Currently I got this code, but it just gets the html source from page, it would be great if someone could help me with parsing all the torrent names from the source.
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_USERAGENT => "spider",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
$data = get_web_page('http://kickass.to/usearch/grand%20theft%20auto%20v%20category:ps3/');
print_r(htmlspecialchars($data['content']));
Is the use of PHP a requirement?
If not, the following groovy script solves your problem:
#Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.6')
import groovyx.net.http.*
import groovy.xml.*
def http = new HTTPBuilder('http://kickass.to/usearch/grand%20theft%20auto%20v%20category:ps3/')
def html = http.get(path: '')
html.'**'.findAll { it.#class == 'torrentname' }.each { torrentNameDiv ->
def titleLink = torrentNameDiv.'*'.findAll { it.#class.text().contains('normalgrey') }?.getAt(0)
def title = titleLink.'*'.findAll { it.name() == 'STRONG' && it.#class == 'red' }.join(' ')
def info = titleLink[0].children().findAll { it instanceof String }.join(' ')
println "title=$title"
println "info=$info"
}
Behind the scenes there are groovy classes like HTTPBuilder, XmlSlurper and GPathResult. The navigation over HTML structure is done via GPathResult.
Documentation here:
http://groovy.codehaus.org/api/groovy/util/slurpersupport/GPathResult.html
http://groovy.codehaus.org/modules/http-builder/home.html
Example here:
http://binarybuffer.com/2012/05/parsing-html-pages-like-a-boss-with-groovy
Unless the html document is xhtml, it is probably not well-formed XML and you'll need an HTML parser rather than an XML parser... or you'll need to preprocess it into xhtml using something like the W3C's "tidy" tool, and then parse it as XML.
Once you get it into a standard W3C DOM, check whether that DOM implementation provides an implementation of XPath. If not, off-the-shelf implementations of XPath that run against user-provided DOMs are also available -- Apache Xalan is one obvious example. Xalan also implements XSLT, so you could combine gathering the data and arranging it into your desired format into a single stylesheet and avoid having to hand-code some of that.
I'm finding list of Areas for my CakePHP 2.x website and it supports, JSON output as below with find all method:
$this->Area->find('all', array('fields' => array('id', 'name', 'order'), 'conditions' => array('Area.status' => 1)));
Below is my JSON output:
[{"Area":{"id":"2","name":"Area 1","order":"1"}},{"Area":{"id":"3","name":"Area 2","order":"1"}}]
Now Is that possible for me to remove Area tag which is repeating everytime?
Any patch for same? Do let me know if any suggestions / ideas.
on your view for output json write this:
echo json_encode(Set::extract('/Area/.', $area));
For me works fine.
CakePHP Provides some in-built library functions for data extraction from result set and output same as JSON format.
// initialize your function to render false and response type json
$this->autoRender = false; // no view to render
$this->response->type('json');
// Remove Area from array and encode
$area = Set::extract('/Area/.', $area);
$json = json_encode( $area);
$this->response->body($json);
Hope it helps !