I Google'd not long ago and came across this solution to loop out information from a XML page.
$url = 'http://steamcommunity.com/id/ChetFaliszek/stats/L4D/?xml=1';
$achxml = simplexml_load_file($url);
foreach ($achxml->playerstats->game as $ach)
{
$name = (string) $ach->NAME;
echo $name. "<br>";
}
I think these lines of code will do the trick but I only get following error when I try to fetch the information: Warning: Invalid argument supplied for foreach() in .... The link to the XML page (random guys XML) is in the $url parameter.
Now to the question: How do I fix this problem so I can see if this code will work?
Thanks in advance.
One more problem before I have fix this issue :) How do I list every achievement that's in the XML page?
try:
foreach ($achxml->achievements->achievement as $achievement)
{
echo $achievement->name, '(closed: ', (string) $achievement['closed'], ')';
}
Related
I've been recently building a plugin for wordpress which basically uses the instagram API to get an image URL and then place it in a short code.
And I've come to a problem.
I get this error:
E_WARNING : type 2 -- Invalid argument supplied for foreach() -- at
line 22
and I have no idea what am I doing wrong.
My code for the foreach:
//define Access token
$accesst= "ACCESS_TOKEN_GOES_HERE";
//userid
$userid=USERID_GOES_HERE;
//image count to get
$count=20;
//get api contents
$content = file_get_contents('https://api.instagram.com/v1/users/self/media/recent/?access_token='.$accesst.'&count='.$count);
//converting JSON to object
$standardres = json_decode($content, true);
//array method
foreach($standardres['data'][0]['images']['standard_resolution']['url'] as $photo)
{
print $photo['url'][0];
echo "<br>";
}
My JSON var_dump got me this:
https://pastebin.com/3RaL6EUA
The access codes, were of course deleted before posting this.
Does anyone have a clue what I'm doing wrong?
EDIT:
Thanks, everyone, got it figured out in the comments.
Your $standardres['data'] have items which have images, so you must use $standardres['data'] in the foreach loop and then parse the image url from the item data.
foreach($standardres['data'] as $item) {
print $item['images']['standard_resolution']['url'];
echo "<br>";
}
I don't know exactly the hierarchy of the instagram API, but I suggest you to try :
foreach($standardres['data']['images'] as $photo) {
print_r($photo); // to see what the array contains!
echo $photo['standard_resolution']['url'];
echo "<br>";
}
I need to extract information from an XML Radionomy (radio streaming) containing information of artist, title, cover art, weather etc.
By placing this url in the browser goes all information xml:
http://api.radionomy.com/currentsong.cfm?radiouid=ce5b70e5-dcc3-40a2-81b2-c713a02daf29&apikey=842650d9-c21a-474d-be8f-f44413dfaae2&callmeback=no&type=xml&cover=yes&previ%20ous=no
<tracks>
<radioname>RTFM</radioname>
<rank>2</rank>
<isradionomy>1</isradionomy>
<radurl>http://www.radionomy.com/rtfm</radurl>
<track>
<uniqueid>2905480252</uniqueid>
<title>02-13-2016</title>
<artists>News - US</artists>
<starttime>2016-02-14 00:59:57.177</starttime>
<playduration>121352</playduration>
<current>1</current>
</track>
</tracks>
But to try to get information through php gives me error. I do not know where he might be the problem, see if I can lend a hand.
I'm trying this:
$xml = #simplexml_load_file("
http://api.radionomy.com/currentsong.cfm?radiouid=ce5b70e5-dcc3-40a2-81b2-c713a02daf29&apikey=842650d9-c21a-474d-be8f-f44413dfaae2&callmeback=no&type=xml&cover=yes&previ%20ous=no");
if($xml){
foreach ($xml as $track){
$artiste = $track->artists;
$titre = $track->title;
$pochette = $track->cover;
continue;
}
}else{
echo "error";
}
Warning: Invalid argument supplied for foreach() in...
EDIT:
Noticed more mistakes and provided working code.
Use urlencode to encode your URL string. Use $xml->track to loop track nodes.
And stop using # to see the actual errors. It is really helpful to see errors.
Didn't touch your original code but you can take it from here.
<?php
$xml = simplexml_load_file(urlencode("http://api.radionomy.com/currentsong.cfm?radiouid=ce5b70e5-dcc3-40a2-81b2-c713a02daf29&apikey=842650d9-c21a-474d-be8f-f44413dfaae2&callmeback=no&type=xml&cover=yes&previ%20ous=no"));
if($xml){
foreach ($xml->track as $track){
$artiste = $track->artists;
$titre = $track->title;
$pochette = $track->cover;
continue;
}
} else {
echo "error";
}
I am trying to traverse this xml feed:
http://www.goonersworld.co.uk/forum/feed.php
using this code:
$data = file_get_contents('http://www.goonersworld.co.uk/forum/feed.php');
//$data = str_replace("content:encoded>","content>",$data);
$xml = simplexml_load_string($data,'SimpleXMLElement', LIBXML_NOCDATA);
foreach ($xml->feed->entry as $stories) {
echo $stories->published."<br>";
}
But I'm getting nothing back. To me it looks like $xml->feed->entry->published but am I missing something?
Ok, so I've figured this out. In case it helps anyone else it was a feed generated by PHPBB (Bulletin Board).
The actual structure I was looking for was simply:
foreach ($xml->entry as $stories) {
echo $stories->published."<br>";
}
feed and entry didn't look to be at the same level in the XML formatting but they were :-(
foreach ($likes as $like) {
// Extract the pieces of info we need from the requests above
$id = idx($like, 'id');
$item = idx($like, 'name');
fwrite($fileout,json_encode($like));
fwrite($fileout,PHP_EOL );
}
$json_string = file_get_contents('testson.json');
$get_json_values=json_decode($json_string,true);
foreach ($get_json_values as $getlikes) { ?>
<li>
<a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
</li>
<?php
}
When opening the browser, there is a Warning: Invalid argument supplied for foreach(). I don't understand why would my arguments be invalid.
If I add the if, nothing happens, which shows what the actual problem is. But the question is WHAT IS THE PROPER WAY TO DO THIS? I'm pretty sure it's very simple, but i've been struggling with this for more than an hour. My json files has fields like this, so I don't think there would be the problem:
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762"}
Please help me, I really got tired with it, and I don't know what to do. So... how can I decode the file into an array?
You need the contents of the testson.json file not just the name!
Receive the contents via PHP:
$json_string = file_get_contents('testson.json');
Make sure there are valid JSON contents in the file by testing it via
var_dump(json_decode($json_string));
And then call
foreach (json_decode($json_string) as $getlikes) { ?>
Update:
When you save the file and access it miliseconds later it might be that the filesystem is too slow and not showing you the correct content.
Add
fclose($fileout);
clearstatcache();
before the file_get_contents(); call!
I recommend to use file_put_contents() and file_read_contents() to get
rid of such problems!
json_decode is expecting a string as it's first parameter. You are passing what I'm guessing is a filename. You should load the file first like so...
$json = file_get_contents('testson.json');
$data = json_decode($json);
I need to find the number of indexed pages in google for a specific domain name, how do we do that through a PHP script?
So,
foreach ($allresponseresults as $responseresult)
{
$result[] = array(
'url' => $responseresult['url'],
'title' => $responseresult['title'],
'abstract' => $responseresult['content'],
);
}
what do i add for the estimated number of results and how do i do that?
i know it is (estimatedResultCount) but how do i add that? and i call the title for example this way: $result['title'] so how to get the number and how to print the number?
Thank you :)
I think it would be nicer to Google to use their RESTful Search API. See this URL for an example call:
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:stackoverflow.com&filter=0
(You're interested in the estimatedResultCount value)
In PHP you can use file_get_contents to get the data and json_decode to parse it.
You can find documentation here:
http://code.google.com/apis/ajaxsearch/documentation/#fonje
Example
Warning: The following code does not have any kind of error checking on the response!
function getGoogleCount($domain) {
$content = file_get_contents('http://ajax.googleapis.com/ajax/services/' .
'search/web?v=1.0&filter=0&q=site:' . urlencode($domain));
$data = json_decode($content);
return intval($data->responseData->cursor->estimatedResultCount);
}
echo getGoogleCount('stackoverflow.com');
You'd load http://www.google.com/search?q=domaingoeshere.com with cURL and then parse the file looking for the results <p id="resultStats" bit.
You'd have the resulting html stored in a variable $html and then say something like
$arr = explode('<p id="resultStats"'>, $html);
$bottom = $arr[1];
$middle = explode('</p>', $bottom);
Please note that this is untested and a very rough example. You'd be better off parsing the html with a dedicated parser or matching the line with regular expressions.
google ajax api estimatedResultCount values doesn't give the right value.
And trying to parse html result is not a good way because google blocks after several search.
Count the number of results for site:yourdomainhere.com - stackoverflow.com has about 830k
// This will give you the count what you see on search result on web page,
//this code will give you the HTML content from file_get_contents
header('Content-Type: text/plain');
$url = "https://www.google.com/search?q=your url";
$html = file_get_contents($url);
if (FALSE === $html) {
throw new Exception(sprintf('Failed to open HTTP URL "%s".', $url));
}
$arr = explode('<div class="sd" id="resultStats">', $html);
$bottom = $arr[1];
$middle = explode('</div>', $bottom);
echo $middle[0];
Output:
About 8,130 results
//vKj
Case 2: you can also use google api, but its count is different:
https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=ursitename&callback=processResults
https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:google.com
cursor":{"resultCount":"111,000,000","
"estimatedResultCount":"111000000",