How to access XML response - php

Good day, I want to access the XML response and echo it to display its value but I don't know how to do it. I already tried some few answers in StackOverflow but I fail.
This is my code.
<?php
error_reporting(E_ALL);
require_once 'ruFunctions.php';
$rentalsUnited = new rentalsUnited();
$ru= $rentalsUnited->getOwners();
if($ru != null){
$data= simplexml_load_string($ru);
var_dump($data); // it will return boof(false)
var_dump($ru);
echo $data->Pull_ListAllOwners_RS->Status['ID']; //Trying to get property of non-object
}
?>
Results for var_dump($ru);
object(SimpleXMLElement)#2 (3) {
["Status"]=>
string(7) "Success"
["ResponseID"]=>
string(32) "44065d9888304e8cba912bce4d131ab1"
["Owners"]=>
object(SimpleXMLElement)#3 (1) {
["Owner"]=>
object(SimpleXMLElement)#4 (7) {
["#attributes"]=>
array(1) {
["OwnerID"]=>
string(6) "429335"
}
["FirstName"]=>
string(5) "Test"
["SurName"]=>
string(7) "Tester"
["CompanyName"]=>
string(15) "Test Helpers"
["Email"]=>
string(23) "info#Test.com"
["Phone"]=>
string(12) "+13474707707"
["UserAccountId"]=>
string(3) "602"
}
}
}

It looks like $ru is already a SimpleXMLElement, so trying to call simplexml_load_string will fail on this.
You can see some of the details by
if($ru != null){
echo $ru->Status;
}
You can (probably) list the owners by...
if($ru != null){
foreach ($ru->Owners->Owner as $owner ) {
echo "ownerId=".$owner['OwnerID'].PHP_EOL;
echo "FirstName=".$owner->FirstName.PHP_EOL;
}
}

Related

How to parse steam api JSON and print it out? PHP

I want to parse JSON that I recieve from steam via api link http://steamcommunity.com/id/theorangeass/inventory/json/753/1/ , but when I try to print it with echo it show nothing.
Here is the code
$data = file_get_contents('http://steamcommunity.com/id/theorangeass/inventory/json/753/1/');
$json = json_decode($data, true);
echo $json->success;
var_dump:
array(6) { ["success"]=> bool(true) ["rgInventory"]=> array(1) { ["922506184369981039"]=> array(5) { ["id"]=> string(18) "922506184369981039" ["classid"]=> string(10) "1254492673" ["instanceid"]=> string(10) "2070301907" ["amount"]=> string(1) "1" ["pos"]=> int(1) } } ["rgCurrency"]=> array(0) { } ["rgDescriptions"]=> array(1) { ["1254492673_2070301907"]=> array(18) { ["appid"]=> string(3) "753" ["classid"]=> string(10) "1254492673" ["instanceid"]=> string(10) "2070301907" ["icon_url"]=> string(116) "U8721VM9p9C2v1o6cKJ4qEnGqnE7IoTQgZI-VTdwyTBeimAcIowbqB-harb00cJ0fNdiCJoFB3O541FNc9ZPYXYjjL7UqfFEwOtgZKcs0eWlClqzSJn6" ["icon_url_large"]=> string(106) "U8721VM9p9C2v1o6cKJ4qEnGqnE7IoTQgZI-VTdwyTBeimAcIowbqB-harb00cJ0fNdiA54UEGOnqGQPJ9hDZHA50feEo7RMyO_GQNzkkA" ["icon_drag_url"]=> string(0) "" ["name"]=> string(4) "BEEP" ["market_name"]=> string(0) "" ["name_color"]=> string(0) "" ["background_color"]=> string(0) "" ["type"]=> string(4) "Gift" ["tradable"]=> int(0) ["marketable"]=> int(0) ["commodity"]=> int(0) ["cache_expiration"]=> string(20) "2017-01-02T00:00:00Z" ["fraudwarnings"]=> array(1) { [0]=> string(223) "This is a restricted gift which can only be redeemed in these countries: Armenia, Azerbaijan, Belarus, Georgia, Kyrgyzstan, Kazakhstan, Moldova, Republic of, Tajikistan, Turkmenistan, Uzbekistan, Ukraine, Russian Federation" } ["descriptions"]=> array(1) { [0]=> array(1) { ["value"]=> string(216) "A combination of Yoshi’s Island-style platforming with a gravity gun right out of Half-Life, BEEP is an amazing physics-platformer. Despite its friendly art style, this is a hardcore platformer in the truest sense." } } ["actions"]=> array(1) { [0]=> array(2) { ["name"]=> string(13) "View in store" ["link"]=> string(41) "http://store.steampowered.com/app/104200/" } } } } ["more"]=> bool(false) ["more_start"]=> bool(false) }
You are trying to echo a boolean. If you are wanting to echo true you're going to need to do an if, or a switch statement. An if statement would probably be easiest.
echo $json->success == true ? 'TRUE' : 'FALSE';
To parse the array to retrieve the item id's in the rgInventory to must do a foreach.
foreach ($json['rgInventory'] as $item) {
echo $item['id'];
}
Where you should start learning about arrays is Here

Referencing an item in a foreach loop using php unset

I return this array of objects from an API call like so. Note that $result is an array of arrays with $result[data] holding todo list objects and result[success] holding status of API call:
array(9) { [0]=> object(stdClass)#3 (5) { ["todo_id"]=> string(10) "1480430478" ["title"]=> string(13) "Check Printer" ["description"]=> string(8)
"Room 233" ["due_date"]=> string(10) "11/29/2016" ["is_done"]=> string(4) "true" } [1]=> object(stdClass)#4 (5) { ["todo_id"]=> string(10) "148043046" ["title"]=> string(18) "Doctor Appointment" ["description"]=> string(7)
"#4pm. " ["due_date"]=> string(10) "11/30/2016" ["is_done"]=> string(4) "true" }
etc..
I sort the array with usort fine and then I want to resort on the "is_done" field and put them at bottom of todo list in date order. The php to do this is :
//Sort by is_done
foreach($result[data] as $arrayElement ) {
foreach($arrayElement as $valueKey => $value) {
if(($valueKey == 'is_done') && ($value == 'true')){
$temp = $arrayElement;
//delete this particular object from the $array
unset($result[data][$arrayElement]);
array_push($result[data], $temp);
}
}
}
The problem I am having is my completed items are now at the end of the array but they are also still in their original position. The unset is not working. I have tried all variations on referencing the $result[data] item to no avail. This is probably something simple but I need some help if possible. Googling and checking this site shows no examples of unset in this type of situation. Thanks in advance.
Update:
after applying colburton's solution the API is now returning this data structure:
object(stdClass)#3 (6) { ["2"]=> object(stdClass)#4 (5) { ["todo_id"]=> int(1480698596) ["title"]=> string(7) "Test #4" ["description"]=> string(4) "test" ["due_date"]=> string(10) "12/02/2016" ["is_done"]=> string(5) "false" } ["3"]=> object(stdClass)#5 (5) { ["todo_id"]=> string(10) "1480617975" ["title"]=> string(13) "Check Printer" ["description"]=> string(4)
"Test" ["due_date"]=> string(10) "12/06/2016" ["is_done"]=> string(5) "false" } ["5"]=> object(stdClass)#6 (5) { ["todo_id"]=> int(1481136023) ["title"]=> string(9) "Todo item" ["description"]=> string(7) "test123" ["due_date"]=> string(10) "01/19/2017" ["is_done"]=> string(5) "false" } etc...
At the end of the call i do a
//json_decode the result
$result = #json_decode($result);
//check if we're able to json_decode the result correctly
if ($result == false || isset($result->success) == false) {
throw new Exception('Request was not correct');
}
//if there was an error in the request, throw an exception
if ($result->success == false) {
throw new Exception($result['errormsg']);
}
//if everything went great, return the data
return $result->data;
}
and then in main program I reference $result as
$result = $todo_items[0];
And that is where fatal error occurs now.
Update II:
Wanted to add that you then need to reindex the array
$result['data'] = array_values($result['data']);
I read here that this is a bug in json_decode. Thanks for the help....
Please use quotes around your array indices. This unsets what you want:
foreach ($result['data'] as $idx => $arrayElement) {
foreach ($arrayElement as $valueKey => $value) {
if (($valueKey == 'is_done') && ($value == 'true')) {
$temp = $arrayElement;
//delete this particular object from the $array
array_push($result['data'], $temp);
unset($result['data'][$idx]);
}
}
}

Update Check with PHP

I'm working on an update system that checks a remote file string
$local = simplexml_load_file(root_p.'/version.xml');
$remote = simplexml_load_file("mygithuburltoblob/version.xml");
if($local->build == $remote->build) {
} else {
echo "Version ".$remote->version." Available now";
}
But even if the build numbers match it still returns that the update is available. Does anyone know why that would be?
(Yes root_p is already defined, the problem isn't loading and retrieving the values)
Remote Var Dump
object(SimpleXMLElement)#12 (6) { ["title"]=> string(11) "Loopy Cubix" ["author"]=> string(12) "Morgan Green" ["version"]=> string(3) "1.0" ["build"]=> string(4) "1111" ["type"]=> string(5) "Alpha" ["feed"]=> object(SimpleXMLElement)#15 (0) { } }
Local Var Dump
object(SimpleXMLElement)#11 (6) { ["title"]=> string(24) "Looped Cubix Pre Release" ["author"]=> string(12) "Morgan Green" ["version"]=> string(3) "1.0" ["build"]=> string(4) "1111" ["type"]=> string(6) "Closed" ["feed"]=> object(SimpleXMLElement)#15 (0) { } }
On the top of the page is my output from
<?php
$local = simplexml_load_file(root_p.'/version.xml');
$remote = simplexml_load_file("https://raw.githubusercontent.com/Doxramos/Invontrol/master/version.xml");
echo "Local: ". gettype($local->build);
foreach($local->build as $build) {
echo $build. "<br />";
}
echo "Remote: ". gettype($remote->build);
foreach($remote->build as $build) {
echo $build. "<br />";
}
Shows both as an object with the same value.
As I see that oject is no equal, example of some compared elements:
["title"]=> string(11) "Loopy Cubix"
["title"]=> string(24) "Looped Cubix Pre Release"
The issue had to do with whitespace while parsing the XML data. I ended up fixing it by replacing
if($remote->build == $local->build) {
}
else {
//Output Update Information
}
with
$trimmed_local = trim($local->build);
$trimmed_remote = trim($remote->build);
And using the new variables as my comparison operators
if($trimmed_local == $trimmed_remote) {
}
else {
//Output Update Information
}

simplexml_load_string - child nodes not showing

I am working with an xml file that I am trying to parse into json format and then decode to an array. I accomplished this mainly using the built in simplexml_load_string and then json_encode. The issue is when calling simplexml_load_string the xml isn’t fully preserved. It seems like the child nodes for video show as object(stdClass). How could I get all values of the xml file? Link to XML
Code:
$xml = simplexml_load_string( file_get_contents('http://foxsoccer2go.mobilefeeds.performgroup.com/fox/api/videos.xml/channel/home') );
$json = json_encode($xml);
Result:
["results"]=>
object(stdClass)#183 (4) {
["previousPage"]=>
object(stdClass)#184 (1) {
["#attributes"]=>
object(stdClass)#185 (1) {
["exists"]=>
string(5) "false"
}
}
["nextPage"]=>
string(1) "2"
["total"]=>
string(2) "40"
["resultList"]=>
object(stdClass)#186 (1) {
["video"]=>
array(20) {
[0]=>
object(stdClass)#187 (7) {
["#attributes"]=>
object(stdClass)#188 (2) {
["id"]=>
string(7) "2329124"
["type"]=>
string(3) "960"
}
["description"]=>
object(stdClass)#189 (0) {
}
["created"]=>
string(25) "2015-02-18 04:04:52 +0000"
["duration"]=>
string(2) "86"
["images"]=>
object(stdClass)#190 (2) {
["image"]=>
object(stdClass)#191 (1) {
["#attributes"]=>
object(stdClass)#192 (3) {
["id"]=>
string(8) "13503818"
["width"]=>
string(3) "100"
["height"]=>
string(3) "100"
}
}
["thumbnail"]=>
object(stdClass)#193 (1) {
["#attributes"]=>
object(stdClass)#194 (3) {
["id"]=>
string(8) "13503819"
["width"]=>
string(3) "372"
["height"]=>
string(3) "210"
}
}
}
["videoFiles"]=>
object(stdClass)#195 (1) {
["file"]=>
object(stdClass)#196 (1) {
["#attributes"]=>
object(stdClass)#197 (3) {
["id"]=>
string(8) "14704560"
["formatId"]=>
string(3) "400"
["uploaded"]=>
string(4) "true"
}
}
}
["categories"]=>
object(stdClass)#198 (1) {
["category"]=>
string(21) "UEFA Champions League"
}
}
I would suggest just try to parse those values using SimpleXML alone and stick with it. Just access those properties properly. As for those nodes which have been wrapped with character data in it, cast them as (string).
$xml = simplexml_load_string( file_get_contents('http://foxsoccer2go.mobilefeeds.performgroup.com/fox/api/videos.xml/channel/home'));
foreach($xml->results->resultList->video as $video) {
$description = (string) $video->description;
$created = $video->created;
$duration = $video->duration;
$image = $video->images->image;
$thumbnail = (string) $video->images->image;
$video_file = (string) $video->videoFiles->file;
$categories = (string) $video->categories->category;
echo "
Description: $description <br/>
Created: $created <br/>
Duration: $duration <br/>
Categories: $categories <br/>
<hr/>
";
}
Sample Output

php - how to check if there is text within XML element

:) Let's say that i have that code:
<sample number="1">TEXT</sample>
but sometimes it could be
<sample number"1"/>
Q: How to check if it's self closed or not ? Or I want to check if it's there TEXT within element sample
Note: I'm using that way to retrieve XML doc:
$content = #file_get_contents($url);
$xml = new SimpleXMLElement($content);
You need to type cast the element to string, then check if it's empty or not.
Here's a quick example:
$test = simplexml_load_string("<test><elem test='12'><sub /><sub /></elem><elem test='12'>hi</elem><elem test='9' /><elem /></test>");
foreach($test as $elem){
echo "\n";
var_dump($elem);
if((string)$elem == '' && $elem->count() == 0)
echo 'Empty';
else
echo 'Full';
}
Will return:
object(SimpleXMLElement)#3 (2) {
["#attributes"]=>
array(1) {
["test"]=>
string(2) "12"
}
["sub"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#4 (0) {
}
[1]=>
object(SimpleXMLElement)#5 (0) {
}
}
}
Full
object(SimpleXMLElement)#5 (2) {
["#attributes"]=>
array(1) {
["test"]=>
string(2) "12"
}
[0]=>
string(2) "hi"
}
Full
object(SimpleXMLElement)#3 (1) {
["#attributes"]=>
array(1) {
["test"]=>
string(1) "9"
}
}
Empty
object(SimpleXMLElement)#5 (0) {
}
Empty

Categories