PHP: get data from XML string - php

I have a simple problem getting data from an eBay API string. I want to format numbers to 2 digits 8.0 > 8.00
This works fine
echo $price; // output: 8.0
But...
echo number_format($price, 2); // output: (nothing)
A var_dump tells me why...
var_dump($price);
// output: object(SimpleXMLElement)#19 (2) { ["#attributes"]=> array(1) { ["currencyId"]=> string(3) "USD" } [0]=> string(3) "8.0" }
How do I get the 8.0 into a 8.00 (I know I can use REGEX but it feels like not the proper way)
And while we are here, how I can get the 'USD' ?
PS: the API call used is findCompletedItems - and strangely to me, the XML response has no visible USD at all.

The var_dump gives you an object of type SimpleXMLElement which has a __toString method which returns the text content that is directly in the element so echo $price; will result in 8.0
The USD is part of the attributes which returns an object of type SimpleXMLElement.
You can get the price and the currency casting it to a (string)
$priceAsString = (string)$price;
$currencyIdAsString = (string)$price->attributes()->currencyId;

You're not passing in a string, you're passing in an object of class SimpleXMLElement. The easiest you can do is cast it to a string before passing it to number_format using (string)$price

Related

Saving form values to an Object as attributes (Associative Array, PHP, PDO, lunk head)

I'm working on an AJAX CRUD and I cannot get the form values in the Assoc. array to save individually as object attributes for the MySQL query.
I am following enter link description here but instead of the mysqli I'm using PDO.
Not much of a php person and this is my first OOP use of PDO and JSON.
The vardump() shows the input text is there...
// get posted data
$data = json_decode(file_get_contents("php://input"), true);
// set event property values
$event=>mainTitle = $data->main-title;
$event->subTitle = $data->sub-title;
$event->eventUrl = $data->event-url;
And the dumps:
array(9) {
["main-title"]=>
string(15) "Test Main Title"
["sub-title"]=>
string(14) "Test Sub title"
["event-url"]=>
string(9) "Test URTL"
...
object(Event)#3 (11) {
["conn":"Event":private]=>
object(PDO)#2 (0) {
}
["table_name":"Event":private]=>
string(8) "tblEvent"
["mainTitle"]=>
int(0)
["subTitle"]=>
int(0)
["eventUrl"]=>
int(0)
...
try changing $event=>mainTitle to $event->mainTitle
You have passed a second argument to json_decode() what means you'd like to get an array instead of the object. So just work like with the array. Replace to $event->mainTitle = $data['main-title'];
I found the answer for part of my problem here: Handling-JSON-like-a-boss-in-PHP
json_decode() is able to return both an object or associative array.
//For an object:
$result = json_decode($string);
//For an Assoc. Array:
$result = json_decode($string, true);
What I struggled with is that the var_dump() returns almost exact result for the two. They indeed have to be the same type.
The second part of my problem that was more subvert was having hyphens in the object attribute names. I didn't find a reason why but for sake of clarity in my code I just removed them.

Can't retrieve value of JSON Object attr after json_encode in PHP

I'm not able to get the value of the image attribute in this (apparently valid) JSON object:
echo var_dump($result);
array(1) {
["images"]=>
array(1) {
[0]=>
array(1) {
["src"]=>
string(112) "http://staticf5a.diaadia.info/sites/default/files/styles/landscape_310_155/public/nota_periodistica/taxis_13.jpg"
}
}
}
$jsonResult = json_encode($result); //result is an array of arrays
echo $jsonResult;
{"images":[{"src":"http:\/\/staticf5a.diaadia.info\/sites\/default\/files\/styles\/landscape_310_155\/public\/nota_periodistica\/taxis_13.jpg"}]}
echo $jsonResult->images; //show nothing
This snippet was working few days ago, and logs (ini_set('display_errors', '0');) don't show anything related.
After encoding, $jsonResult is just a string and you won't be able to access any elements of encoded JSON without decoding it first.
Have a look at PHP's ``json_decode'' function: http://php.net/manual/pl/function.json-decode.php
It will convert the JSON back to associative array or object.
Anyway, I have no idea why you encode the associative array as JSON and try to access images there instead of just taking it from the array itself.
You are trying to get property from a string here. json_encode() returns the json representation of an object as a string. That string you can turn into an actuall object with json_decode()

php, json to specific string

By POST I get this JSON (can have more than 3 values in it)
{"preferences":["Theater","Opera","Danse"]}
Well, I need to get
array('Theater', 'Opera', 'Degustation')
json_decode doesn't work.
Do you have any ideas please?
Thank you by advance
Try adding the true parameter:
$jsonData = '{"preferences":["Theater","Opera","Danse"]}';
$arrayData = json_decode($jsonData, true );
var_dump($arrayData['preferences']);
The last line outputs the following:
array(3) {
[0]=>
string(7) "Theater"
[1]=>
string(5) "Opera"
[2]=>
string(5) "Danse"
}
Which is what you want. Good luck!
That JSON string is wrapped in an object (denoted by curly braces {}). json_decode will give you the wrapper object whose "preferences" property is the array you're looking for.
$wrapper = json_decode($json_string);
$array = $wrapper->preferences;
json_decode might also be unavailable if you're using and older version of php. In that case you should try a php json library.
You might have used the output of the json_decode() function as an associated array while you hadn't have told the function to provide an associated array for you, or vice versa!! However, the following will get you the array at the preferences index:
<?php
$decoded = json_decode('{"preferences":["Theater","Opera","Danse"]}', true); // <-- note the second parameter is true.
echo '<pre>';
print_r($decoded['preferences']); // output: Array ( [0] => Theater [1] => Opera [2] => Danse )
// ^^^^^^^^^^^^^^^^^^^^^^^
// Note the usage of the output of the function as an associated array :)
echo '</pre>';
?>

PHP - json_decode() returns null when using echo

I am using the following script to decode a json. Although the var_dump($obj) returns result (similar to one in here Example #1), the echo line doesn't return any result, as if the $obj being null.
<?php
$clientJSONObject = file_get_contents('php://input');
$obj = json_decode($clientJSONObject, TRUE);
var_dump($obj); // working.
echo $obj; // returns nothing.
echo $obj["carrier"]; // returns nothing.
?>
var_dump output:
array(2) {
["carrier"]=>
string(8) "Etisalat"
["userLanguage"]=>
string(2) "ar"
}
You cant echo an object property like that , you have to use -> operator
here is the example of a similar thing what you are looking for
echo $obj->{"objectname"}
will print the property name of the json decode object . and I am able to see one more error in your code . you are giving true in caps that is the reason the Jsondecode function is not giving you an array it is still throwing an object

php simplexml get object variable start with number

When I parse an rss file with SimpleXMLElement, I get this object :
object(SimpleXMLElement)#307 (1) {
[0]=>
string(39) "http://workspace/wordpress/hello-world/"
}
$var->0 doesn't works.
I don't know how to do it :(
thanks.
It behaves like an array
echo $var[0];
In this case - when there's only one (child) element - you don't even have to use the index
echo $var;

Categories