I am trying to convert a PHP array object to an JSON.Following is the PHP Array Object;
Array
(
[0] => Project\Man\Model\Branch Object
(
[id:protected] => 123456
[name:protected] => Parent Branch
[type:protected] => services
)
)
I tried Serializing it but its not in a friendly readable object.
I tried the following:
json_encode
serialize
a:1:{i:0;O:23:"Project\Man\Model\Branch ":3:{s:5:"*id";s:36:"123456";s:7:"*name";s:20:"Parent Branch";s:7:"*type";s:8:"services";}}[{}]
I am trying for some solution where i can get JSON. any help.
If you just want json, you should only use json_encode(), not serialize().
Since your object properties are set as protected, they will however not be available when you encode the object whitout some additional help.
This is where the interface JsonSerializable comes into play.
You need to make sure that the object you want to encode implements the interface. Then you need to add a jsonSerialize() method to the class.
class Branch implements \JsonSerializable
{
protected $id;
protected $name;
protected $type;
// ... your class code
public function jsonSerialize()
{
// Return what you want to be encoded
return [
'id' => $this->id,
'name' => $this->name,
'type' => $this->type,
];
}
}
If you now pass this object through json_encode() and you'll get a json string with what our new method returns.
Related
I'm trying to get JSON data back from the Data Science Toolkit, but the response I am getting doesn't have it. I am trying to pass a string object (json encoded from an array of addresses) to the dstk field, to return a list of coordinates.
Here's the following code snippet:
$client = new \GuzzleHttp\Client(['base_uri' => 'http://www.datasciencetoolkit.org/']);
$request = $client->post('street2coordinates', ['form_params' => ['body' => json_encode($addresses)] ]);
And when I die dump
dd($request->getBody()),it just returns the ff object. or even just $request, I can't pull json data on my search I am expecting Latitude/Longitude coordinates - but I have no idea how/where to get them.
object(GuzzleHttp\Psr7\Stream)[215]
private 'stream' => resource(8, stream)
private 'size' => null
private 'seekable' => boolean true
private 'readable' => boolean true
private 'writable' => boolean true
private 'uri' => string 'php://temp' (length=10)
private 'customMetadata' =>
array (size=0)
empty
I have tried using the Goutte client as well, to no avail. Even trying different methods like ->json() or ->toJson(), no dice. Help is appreciated. Thanks!
You have to force the body to a string, for example by echo'ing it, or casting it explicitly.
echo $response->getBody();
Or
dd((string)$response->getBody());
I have the variable $customerData that stores an object. When I execute print_r($customerData) I get something similar to the below.
Balanced\Customer Object(
[_collection_uris:protected] => Array(
[reversals] => Array(
[class] => Balanced\Reversal
[uri] => /v1/customers/1234123412341234/reversals
)
)
[_member_uris:protected] => Array(
[source] => Array(
[class] => Balanced\Card
[uri] => /v1/customers/1234123412341234/cards/987698769876
)
)
[_type] => customer
[twitter] => twitterHandle
[phone] => 5551231234
)
I'm having issues accessing the uri inside _member_uris:protected.
print_r($customerData->_member_uris:protected); #Throws error "unexpected ':'"
print_r($customerData->_member_uris); #Throws error " Undefined property"
print_r($customerData['_member_uris']); #Throws error "Cannot use object of type array"
What is the process of accessing that part of the object?
Members declared protected can be accessed only within the class itself and by inherited and parent classes. You could add a method in your class to get it, using setAccessible(), like:
//function inside your class
public static function getProtectedProp($class, $propName) {
$reflClass = new ReflectionClass($class);
$property = $reflClass->getProperty($propertyName);
$property->setAccessible(true);
return $property->getValue($class);
}
and you can do:
getProtectedProp($someClassObject, 'protectedPropertyName');
Source:: Reading Protected Property
You can't access protected or private properties from global code or regular functions. From the documentationof Visibility:
Class members declared public can be accessed everywhere.
Members declared protected can be accessed only within the class itself and by inherited and parent classes.
Members declared as private may only be accessed by the class that defines the member.
Hey How Can i get any specific property from the whole object.
I have this query
$portfolios = $this->getDoctrine()
->getRepository('MunichInnovationGroupBundle:PmPortfolios')
->findBy(array('user' => '1'));
foreach ($portfolios as $portfolio){
if($portfolio.isDefault == true){
$default_portfolio = $portfolio;
}
echo $portfolio.name;
}
The complete object looks like this
MunichInnovationGroup\Bundle\Entity\PmPortfolios Object
(
[id:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => 991654b4-aa73-11e1-bdce-4a7b883b8e17
[portfolioName:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Umair Portfolio 1
[description:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Thsi is the description for Umairs portfolio 1
[permalink:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => premalink
[sharingCode:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => asdbnvg123dg
[shared:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] =>
[sharedPortfolioCalls:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] =>
[isDefault:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => 1
[user:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Proxies\MunichInnovationGroupBundleEntityUmUsersProxy Object
How can I get the isDefault value ?
Thanks in advance
If you have your entity set up correctly with all generated set/get methods, and isDefault is a private property (as it seems so from the var_dump) you can simply use
if($portfolio->getIsDefault())
For better method naming I would write a method in the entity:
public function isDefault() {
return $this->isDefault;
}
and then use
if($portfolio->isDefault())
I'm trying to reach an element in an object array. But I couldn't succeed.
Let's think this as an object called $result
How can I reach maskedNumber?
Braintree_Result_Successful Object
(
[success] => 1
[_returnObjectName:private] => customer
[customer] => Braintree_Customer Object
(
[_attributes:protected] => Array
(
[creditCards] => Array
(
[0] => Braintree_CreditCard Object
(
[_attributes] => Array
(
[maskedNumber] => ***********5897
Since the _attributes property of Braintree_Customer is protected you will need to define an accessor method. The other _attributes property of Braintree_CreditCard also looks like it's supposed to be protected, so I've assumed an identical accessor should exist:
$cards = $object->customer->getAttribute('creditCards');
$number = $cards[0]->getAttribute('maskedNumber');
Accessor method to be placed in both classes:
function getAttribute($attribute) {
return $this->_attributes[$attribute];
}
Edit:
Just to improve upon my original answer a little, I would put some decent error checking in an actual accessor method.
function getAttribute($attribute) {
if (isset($this->_attributes[$attribute])) {
return $this->_attributes[$attribute];
}
return NULL;
}
You could also consider using the magic methods __get() and __set() to act as getters and setters.
I solved the problem by asking braintreepayments. They said that I could retrieve this data after I add user to braintree. But my solution is if I really needed this at the very beginning would be to take it with REGEX. For people who are looking for a great online payment company I suggest you to go with braintree
I know this is old, but this might help some.
Braintree has methods for returning the protected information that's returned from functions like Braintree_Customer::create();
$result = Braintree_Customer::create(array(
'firstName' => $_POST['first_name'],
'lastName' => $_POST['last_name'],
'email' => $_POST['email'],
'creditCard' => array(
'cardholderName' => $_POST['cardholder_name'],
'number' => $_POST['number'],
'expirationMonth' => $_POST['month'],
'expirationYear' => $_POST['year'],
'cvv' => $_POST['cvv'],
'billingAddress' => array(
'postalCode' => $_POST['postal_code']
)
)
));
var_dump($result->customer->__get('id'));
var_dump($result->customer->__get('creditCards'));
The _attributes of customer are protected, but the get function returns them.
This method does not require re-requesting data from Braintree.
try
$Result->customer->_attributes['creditCards'][0]->_attributes['maskedNumber']
with $result->customer you should get the *Braintree_Customer* Object and then in that object you should have methods to retrieve the cards as those methods are protected and cannot be accessed directly. Something like
$customer = $result->customer;
foreach($customer->getCreditCards() as $card)
{
echo $card->getMaskedNumber(); // You will need to create that method too
}
Example of getCreditCards method:
Class Braintree_Customer
{
protected $creditCards;
function getCreditCards()
{
return $creditCards;
}
...
}
I'm attempting to get values from a webservice.
The responce is formated as..
<campaign Id="200"> <name> test </name> </campaign>
PHP Code
SoapClient( "WSDL");
$return = $client->GetCampaigns('Username', 'Password' );
Yet when I attempt to access the return, I get just a stdClass with the name attribute..
public 'Campaign' =>
array
0 =>
object(stdClass)[46]
public 'Name' => string 'chris test' (length=10)
I find that I have to supply a "classmap" to SoapClient to get it to map the objects in the response to classes that are defined in PHP. In WSDLs the type name is usually lower camel case (starting with lower case and camel case the rest).
class MY_Campaign {
private $name;
function getName () { return $this->name; }
}
$options = array(
'classmap' => array(
'campaign' => 'MY_Campaign',
);
);
$client = new SoapClient('http://example.com/yourservice?wsdl', $options);
$return = $client->GetCampaigns ();
I might be able to supply a better answer if I had the WSDL. The classmap depends on the type definitions in the WSDL file.