0

How can I get json in my wordpress loop? Now I have this and it works fine, but very slow:

<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<?php $title = $post->post_title;
$context = stream_context_create(array('http' => array('ignore_errors' => true)));
if ($request = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=2b35547bd5675d8ecb2b911ee9901f59&artist='.urlencode($title).'', false, $context)) {
$xml = new SimpleXMLElement($request);?>
<img src="<?php if($xml->artist->image[3] != '') { echo $xml->artist->image[3]; } else { echo '/another-image.png'; } ?>"> // output image
<?php } endwhile;?>

Now I need to use ajax instead xml for get image url and I have request something like this. How can I insert this ajax output in my loop? Can someone help me?

$.ajax({
url: 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=<?php echo urlencode($title);?>&api_key=2b35547bd5675d8ecb2b911ee9901f59&format=json',
success: function(data) {

    if(data.artist.image[3]["#text"] != '') {
    // don't know how output data.artist.image[2]["#text"]
    } else {
    // output another image
    }
},
})
Jason Cole
  • 51
  • 1
  • 10

1 Answers1

0

The problem you are having now is, you are trying to use data in php which is parsed by javascript. You better fetch the data and parse it in php alone. Here is how example :

$request = file_get_contents( 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=' . urlencode($title) . '&api_key=2b35547bd5675d8ecb2b911ee9901f59&format=json' );
$json_decoded_request = json_decode( $request, TRUE ); // true in 2nd argument will turn the json object into array
if ( $json_decoded_request['artist']['image'][3]['#text'] != '' ) {
    // do what you want to do with image file fetched.
} else {
    // output another image.
} 

If you want to know more info about this, check out this url : http://php.net/manual/en/function.json-decode.php

DeGi
  • 130
  • 1
  • 9
  • thanx for answer. This gives the same result as I have from xml - slow. The problem is that I want to load the data asynchronously. But I don't know js. what I wrote gives result, but I don't know how it parse in the loop – Jason Cole Aug 21 '14 at 21:48
  • It's not recommended to embed javascript inside php loop.. I think you better find a solution like javascript template such as handlebar.js or mustache for that job. – DeGi Aug 22 '14 at 00:01
  • handlebar.js seems good. But I don't understand how can I apply it in my code. I think that there is not need extra libraries. And I need to use js inside my loop for get data for each post in any way like this: have_posts() ) : $wp_query->the_post(); ?> or how can I get data differently for each post? – Jason Cole Aug 22 '14 at 12:48
  • That's an easy way to do it. but not recommended. check out this thread : http://stackoverflow.com/questions/14680482/javascript-inside-php-while-loop – DeGi Aug 23 '14 at 06:42