Trouble with XML vs JSON data - php

Using PHP, I'm trying to grab data from the Goodreads API, which returns XML. I've been having a hell of a time trying to figure out how to pull data out of it.
At some point in the adventure, someone suggested I do a json decode( json encode ($blah)) of the whole thing and use JSON instead of XML.
That brings me to my current situation. Everything works as it should, up to the point where I'm pulling data out of the returned array. I probably should have spent more time reading and learning about arrays, but after more than two days of doing every Google search I could think of, I came here.
Here's the entirety of what gets returned by Goodreads:
a:2:{s:7:"Request";a:3:{s:14:"authentication";s:4:"true";s:3:"key";a:0:{}s:6:"method";a:0:{}}s:6:"search";a:7:{s:5:"query";a:0:{}s:13:"results-start";s:1:"1";s:11:"results-end";s:1:"1";s:13:"total-results";s:1:"1";s:6:"source";s:9:"Goodreads";s:18:"query-time-seconds";s:4:"0.06";s:7:"results";a:1:{s:4:"work";a:9:{s:11:"books_count";s:1:"7";s:2:"id";s:7:"5024045";s:24:"original_publication_day";s:2:"16";s:26:"original_publication_month";s:1:"9";s:25:"original_publication_year";s:4:"2008";s:13:"ratings_count";s:3:"227";s:18:"text_reviews_count";s:2:"53";s:14:"average_rating";s:4:"4.33";s:9:"best_book";a:5:{s:2:"id";s:7:"4958245";s:5:"title";s:37:"7 Habits of Happy Kids [With Earbuds]";s:6:"author";a:2:{s:2:"id";s:5:"38343";s:4:"name";s:10:"Sean Covey";}s:9:"image_url";s:56:"http://photo.goodreads.com/books/1343744353m/4958245.jpg";s:15:"small_image_url";s:56:"http://photo.goodreads.com/books/1343744353s/4958245.jpg";}}}}}
What I want from this array is the "id" variable appears under "best_book". For that, I'm using these lines of code:
$goodreads_results = json_decode(json_encode((array) simplexml_load_string($goodreads_data_a)), 1);
$goodreads_id = $goodreads_results->search->results->work->best_book->id;
I should point out that the array I posted (that began "a:2:{s:7") is what's contained in $goodreads_results after the above two lines of code. So I know everything UP TO that point works as it should.
For whatever reason, I'm not getting the ID. The $goodreads_id variable is empty.
Can somebody help me figure out why? Even though I know it's likely something basic, I'm lost, and everything is starting to look the same to me.

Try:
<?php
$goodreads_data_a = 'a:2:{s:7:"Request";a:3:{s:14:"authentication";s:4:"true";s:3:"key";a:0:{}s:6:"method";a:0:{}}s:6:"search";a:7:{s:5:"query";a:0:{}s:13:"results-start";s:1:"1";s:11:"results-end";s:1:"1";s:13:"total-results";s:1:"1";s:6:"source";s:9:"Goodreads";s:18:"query-time-seconds";s:4:"0.06";s:7:"results";a:1:{s:4:"work";a:9:{s:11:"books_count";s:1:"7";s:2:"id";s:7:"5024045";s:24:"original_publication_day";s:2:"16";s:26:"original_publication_month";s:1:"9";s:25:"original_publication_year";s:4:"2008";s:13:"ratings_count";s:3:"227";s:18:"text_reviews_count";s:2:"53";s:14:"average_rating";s:4:"4.33";s:9:"best_book";a:5:{s:2:"id";s:7:"4958245";s:5:"title";s:37:"7 Habits of Happy Kids [With Earbuds]";s:6:"author";a:2:{s:2:"id";s:5:"38343";s:4:"name";s:10:"Sean Covey";}s:9:"image_url";s:56:"http://photo.goodreads.com/books/1343744353m/4958245.jpg";s:15:"small_image_url";s:56:"http://photo.goodreads.com/books/1343744353s/4958245.jpg";}}}}}
';
$goodreads_results = unserialize($goodreads_data_a);
echo $goodreads_id = $goodreads_results['search']['results']['work']['best_book']['id'];
?>

Related

Extract value from soap response

I need help to extract value from a soap response.
https://i.stack.imgur.com/djv5y.jpg
What i exactly need is:
$username=user
$message=success
Maybe include the SOAP response here, that would be helpful for those who come in the future. As for your question are you using a particular language? That would make it easier to answer.
If you are looking for a way to view use can use this URL: https://codebeautify.org/xmlviewer
Ok now that I see it, it's fairly easy
Assuming you have loaded the SOAP XML into a variable, lets call it $xml_string
$xml = simplexml_load_string($xml_string); // Load it as an object
$xmlarray = json_decode(json_encode($xml),TRUE); // Change it into an array
Then the variables you are looking for is in
$username = $xmlarray['UserName'];
$message = $xmlarray['response']['MESSAGE'];
BTW This solution is found here
PHP convert XML to JSON
I did it as an array as sometimes objects are a little hard to process. You can easily just do the first line and address it as an object. (If those are the only variables you need then an array works fine. Ex: the 'Plan' data will be messed up in an array as it appears twice)
There can be some issues such as the MESSAGE not appearing or the XML returning a failure but I think you should know how to code around missing datum.

I've got a JSON file that I'm trying to extract values from with PHP

I'm trying to pull each of the viewer names from a JSON file in PHP.
I've looked around the Internet extensively for a working example that will offer me the result I desire without much success.
I'm really struggling to find an example that fits my needs on the Internet to help me with what is likely a very simple thing to accomplish.
I've got a JSON file that spits out several values on the Internet and I'm looking to extract every single line from one particular section.
Seeing a working example will likely help me understand what I am doing.
The JSON file that I am using for example is:
https://tmi.twitch.tv/group/user/dansgaming/chatters
I am trying to extract each single line from the "viewers" section in this file.
I've captured the data using the following PHP:
$testviewers = json_decode(#file_get_contents('https://tmi.twitch.tv/group/user/' . $streamName . '/chatters'), true);
var_dump($testviewers['chatters']['viewers']);
It turns out this isn't having the desired result for me.
I simply want each line in the viewer's section to be echoed out with page breaks.
What am I doing wrong? I've tried about two hundred different approaches to this one and have to admit this is my first real time working with JSON.
I've tried to search the Internet for answers and found many tutorials but none have made any sense to me and I know that seeing how to accomplish the result will help me learn exactly what should be going on.
In an ideal world, it will simply output each "viewer" on a separate line that I can work with. If I could echo each of them and then concatenate with a page break or the word "viewer:" before each one this would be a huge help and I'll be able to take it further and likely learn a great deal in the process.
this my way echo from json
$json = json_decode($response, true);
foreach($json['chatters'] as $key => $value)
{
if(!empty($value['viewers']))
{
$VIEWER = $value['viewers'];
$VIEWER = addslashes($VIEWER );
$VIEWER = trim(preg_replace('/\s\s+/', ' ', $VIEWER ));
}
else
{
$VIEWER = '';
}
echo 'VIEWER = '.$VIEWER .'</br>';
}
just make sure the foreach is true, maybe can help.
Turns out the issue here was a PHP error that wasn't displaying. The code was timing out because of how large the JSON file was and a low limit on my machine.
I think this is what you want....
$array = json_decode($your_json,true);
foreach($array['chatters']['viewers'] as $r) echo $r.'<br>';

PHPChart won't accept variables within data array

I've searched everywhere for an answer to this, and I truly do hate asking what is probably a really simple question, but I am lost.
This is the code I'm using to display a pie cart ...
$s1 = array(
array('Carpets',235000),
array('Vinyl',35069),
array('LVT',36911),
array('Laminate',5243.97)
);
$pc = new C_PhpChartX(array($s1),'chart1');
$pc->set_grid(array('drawBorder'=>true,
'drawGridlines'=>false,
'background'=>'#ffffff',
'shadow'=>false));
$pc->set_axes_default(array());
$pc->set_series_default(array(
'renderer'=>'plugin::PieRenderer',
'rendererOptions'=>array('showDataLabels'=>true)));
$pc->set_legend(array('show'=>true,
'rendererOptions'=> array('numberRows'=> 1),
'location'=> 's'));
$pc->draw(400,400);
The chart works fine like this for testing purposes, but when I try and replace the data inside the data array with variables, no chart appears. I think it may be to do with the way the data in the array is being passed to the JavaScript, but I am not skilled enough to fix.
The data is in variables ... $cTotal, $vTotal, $lTotal & $laTotal
I have echoed these and can confirm they are just producing an integer.
I have tried ...
$s1 = array(
array('Carpets',$cTotal),
array('Vinyl',$vTotal),
array('LVT',$lTotal),
array('Laminate',$laTotal)
);
As well as using "" and "{}", but to no avail.
OK, so I figured it out. For some reason when I used ...
$cTotal= $dataLabel['carpet'];
It echoed 236987. But didn't work. However, had a last minute thought and physically forced it to be an integer with ..
$cTotal= (int)$dataLabel['carpet'];
... and it worked. I thought PHP was clever enough to figure that out for itself!

Parse this data with PHP

Going to this webstie:
http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=AK-47%20%7C%20Redline%20%28Field-Tested%29
Yields this result:
{"success":true,"lowest_price":"5,59€ ","volume":"5,688","median_price":"5,92€ "}
The result is updated every time the page is refreshed. Using PHP, how would I be able to save the result line and split it up in my code I can use it for other things? Would it be viable/possible to do this about 3000-5000 times from a loop in my code, or would it be too much and crash it? I won't be using all the data from it in my code, just saving it into a database and moving to the next result.
That code is JSON and can be parsed with json_decode
$data = file_get_contents('http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=AK-47%20%7C%20Redline%20%28Field-Tested%29');
$json = json_decode($data);
echo $json->volume;
As far as looping... why? You would simply load the page 3000+ times in a row. What would be the benefit of that? Perhaps you should consider a cron job instead, which could fetch the data at regular intervals (and not spam the Steam servers)
Your code is in JSON format.
So:
$content = file_get_contents('http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=AK-47%20%7C%20Redline%20%28Field-Tested%29');
json_decode($content);
Should work correctly

Accessing XML attributes data

I have two lines of XML data that are attributes but also contain data inside then and they are repeating fields. They are being stored in a SimpleXML variable.
<inputField Type="Name">John Doe</inputField>
<inputField Type="DateOfHire">Tomorrow</inputField>
(Clearly this isnt real data but the syntax is actually in my data and I'm just using string data in them)
Everything that I've seen says to access the data like this, ,which I have tried and it worked perfectly. But my data is dynamic so the data isn't always going to be in the same place, so it doesn't fit my needs.
$xmlFile->inputField[0];
$xmlFile->inputField[1];
This works fine until one of the lines is missing, and I can have anywhere from 0 to 5 lines. So what I was wondering was is there any way that I can access the data by attribute name? So potentially like this.
$xmlFile->inputField['Name'];
or
$xmlFile->inputField->Name;
I use these as examples strictly to illustrate what I'm trying to do, I am aware that neither of the above lines of code are syntactically correct.
Just a note this information is being generated externally so I cannot change the format.
If anyone needs clarification feel free to let me know and would be happy to elaborate.
Maybe like this?
echo $xmlFile->inputField->attributest()->Name;
And what you're using? DOMDocument or simplexml?
You don't say, but I assume you're using SimpleXMLElement?
If you want to access every item, just iterate:
foreach ($xmlFile->inputField as $inputField) { ... }
If you want to access an attribute use array notation:
$inputField['Type']
If you want to access only one specific element, use xpath:
$xmlFile->xpath('inputField[#Type="Name"]');
Perhaps you should read through the basic examples of usage in the SimpleXMLElement documentation?
For example you can a grab a data:
$xmlFile = simplexml_load_file($file);
foreach($xmlFile->inputField as $res) {
echo $res["Name"];
}

Categories