I'm working with the youtube v3 api. After a few tests, I realized that I need some help. When I'm trying to display the xml content, I'm just getting null values. Can anybody help me?
If you want to see the xml:
https://www.youtube.com/feeds/videos.xml?channel_id=$channelid
And my code is:
$xml=simplexml_load_file("videos.xml");
foreach($xml as $content) {
echo $content->title . "<br>";
echo $content->link['href'] . "<br>";
}
Xml that I want to display:
<entry>
Video ID <yt:videoId>Q4vSZA_8kYY</yt:videoId>
Video title <title>¡Trailer del canal! CBPrductions</title>
Upload date <published>2016-01-14T07:37:03+00:00</published>
<media:group>
Description <media:description>
LIKE PORQUE LO DIGO YO _ Suscribete!: https://www.youtube.com/user/SpanishCBProductions Dale a LIKE a mi página Facebook: https://www.facebook.com/SpanishCBProductions Sigueme en TWITTER!: https://twitter.com/CcristianN3 Y en mi poco sexy INSTAGRAM: http://instagram.com/ccristiann3/
</media:description>
</media:group>
</entry>
I think you can register the namespace and use xpath.
Then for the 'media' and the 'yt' you can get the children by passing the namespace.
If you want to display the first entry:
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id=UCRGn72Qu0KTtI_ujNxRr3Fg';
$xml = simplexml_load_file($url);
$ns = $xml->getDocNamespaces(true);
$xml->registerXPathNamespace('a', 'http://www.w3.org/2005/Atom');
$elements = $xml->xpath('//a:entry');
$content = $elements[0];
$yt = $content->children('http://www.youtube.com/xml/schemas/2015');
$media = $content->children('http://search.yahoo.com/mrss/');
echo "Video ID: " . $yt->videoId . "<br>";
echo "Video title: " . $content->title . "<br>";
echo "Upload date: " . $content->published . "<br>";
echo "Description: " .$media->group->description . "<br>";
If you want to display the information from all the entries, you can use:
foreach ($elements as $content) {
$yt = $content->children('http://www.youtube.com/xml/schemas/2015');
$media = $content->children('http://search.yahoo.com/mrss/');
echo "Video ID: " . $yt->videoId . "<br>";
echo "Video title: " . $content->title . "<br>";
echo "Upload date: " . $content->published . "<br>";
echo "Description: " . $media->group->description . "<br>";
echo "<br>";
}
Related
I am trying to get data from an xml file and am having trouble as the table has a bit more levels than the examples I can find.
I want to be able to iterate through each instance of <Event> as <Information> and <Events> only open and close the data. The <Event> repeats based on the number of events logged.
A sample of the table structure is:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Information>
<Events>
<Event>
<Time>3141.29</Time>
<PrimaryObject ID="487">
<Name>Player1</Name>
<Country>us</Country>
</PrimaryObject>
<Action>Move</Action>
<SecondaryObject ID="814">
<Name>Dog</Name>
<Parent>487</Parent>
</SecondaryObject>
</Event>
</Events>
</Information>
The PHP code is:
<!DOCTYPE html>
<html>
<body>
<?php
$xml=simplexml_load_file("data.xml") or die("Error: Cannot create object");
foreach($xml->Event as $events) {
$id = $events->PrimaryObject->attributes();
$name = $events->PrimaryObject->Name;
...
echo $id['ID'].' '. $name;
echo "<br>";
}
?>
</body>
</html>
You have to use the Events
$xml->Events->Event as $events
For example
$xml=simplexml_load_file("data.xml") or die("Error: Cannot create object");
foreach($xml->Events->Event as $events) {
$id = $events->PrimaryObject->attributes();
$name = $events->PrimaryObject->Name;
echo $id['ID'].' '. $name;
echo "<br>";
}
Output
487 Player1
Php demo
I'm not sure what data exactly you are looking for, but here's everything, using xpath, and you can pick and choose:
$events = $xml->xpath('.//Event');
foreach($events as $event) {
$dat = $event->xpath('./PrimaryObject')[0];
$time= $event->xpath('./Time');
$id = $dat->xpath('./#ID');
$name = $dat->xpath('./Name');
$country = $dat->xpath('./Country');
$dat2 = $event->xpath('./SecondaryObject')[0];
$action= $event->xpath('./Action');
$id2 = $dat2->xpath('./#ID');
$name2 = $dat2->xpath('./Name');
$parent = $dat2->xpath('./Parent');
echo 'Time: ' . $time[0];
echo "<br>";
echo 'Action: ' . $action[0];
echo "<br>";
echo "<br>";
echo 'Primary Object Data:';
echo "<br>";
echo 'ID: ' . $id[0];
echo "<br>";
echo 'Name: ' . $name[0];
echo "<br>";
echo 'Country: ' . $country[0];
echo "<br>";
echo "<br>";
echo "<br>";
echo 'Secondary Object Data:';
echo "<br>";
echo 'ID: ' . $id2[0];
echo "<br>";
echo 'Name: ' . $name2[0];
echo "<br>";
echo 'Parent: ' . $parent[0];
echo "<br>";
}
Output:
Time: 3141.29
Action: Move
Primary Object Data:
ID: 487
Name: Player1
Country: us
Secondary Object Data:
ID: 814
Name: Dog
Parent: 487
I'm trying to grab specific parts of a string to convert them into variables. I was able to use str_replace() to get the output I wanted but since it changes in length especially file paths it just wont cut it.
STRING TEMPLATE:
$issue->fields->description = "MSI: YES XPF: NO PKG TYPE: XYZ VENDOR: WXYZ USER CODE: AB APP NAME: ATBTOOL VERSION: 1.0 MEDIA ZIP FILE: \\123.456.78.9\Path\TO\MY\MSI\MSIHelpV1.0.zip INSTALL DIR: G:\MSI EXISTING: NO";
This template always stays the same and when this array is dumped there is always a space around the values. The values im trying to grab are:
YES
NO
XYZ
WXYZ
AB
ATBTOOL
1.0
\123.456.78.9\Path\TO\MY\MSI\MSIHelpV1.0.zip
G:\MSI
NO
So i'm wondering if there is any to maybe specify to grab everything inbetween MSI: & XPF:, PKG TYPE: & VENDOR:, and so forth just a thought any help would be appreciated!
This is the code I've been working with.
$stringPosPKG = strpos($issue->fields->description, 'TYPE');
$stringPosVENDOR = strpos($issue->fields->description, 'VENDOR');
$stringPosCODE = strpos($issue->fields->description, 'CODE');
$stringPosAPP = strpos($issue->fields->description, 'APP');
$stringPosVERSION = strpos($issue->fields->description, 'VERSION');
echo "</br>";
echo "PKG Begins At " . $stringPosPKG;
echo "</br>";
echo "VENDOR Begins At " . $stringPosVENDOR;
echo "</br>";
echo "CODE Begins At " . $stringPosCODE;
echo "</br>";
echo "APP NAME Begins At " . $stringPosAPP;
echo "</br>";
echo "VERSION Begins At " . $stringPosVERSION;
echo "</br>";
echo "</br>";
$pkgType = substr( $issue->fields->description, 33, -217 );
$vendorName = substr( $issue->fields->description, 48, -203 );
$userCODE = substr( $issue->fields->description, 67, -184 );
$appName = substr( $issue->fields->description, 83, -163 );
$versionNum = substr( $issue->fields->description, 103, -147 );
echo "</br>";
echo "PKG Title: " . $pkgType;
echo "</br>";
echo "VENDOR Title: " . $vendorName;
echo "</br>";
echo "CODE CODE: " . $userCODE;
echo "</br>";
echo "APP NAME: " . $appName;
echo "</br>";
echo "VERSION: " . $versionNum;
echo "</br>";
$versionNumStrRArray = ["."];
$versionNumStrR = str_replace($versionNumStrRArray, "_", $versionNum);
echo "MSI NAME: MSI_" . $pkgType . "_" . $vendorName . "_" . $userCODE . "_" . $appName . "_" . "$versionNumStrR";
OUTPUT:
PKG Begins At 27
VENDOR Begins At 40
CODE Begins At 61
APP NAME Begins At 73
VERSION Begins At 94
PKG Title: ABC
VENDOR Title: WXYZ
CODE CODE: AB
APP NAME: ATBTOOL
VERSION: 1.0
MSI NAME: MSI_ABC_WXYZ_AB_ATBTOOL_1_0
Guess you should be using regular expressions for this one. Something like that:
<?php
function parseFoo(string $foo): array
{
$splitInput = [];
preg_match_all(
'/(?<key>[^\s][A-Z\s]+): (?<value>[\pL\pP\d]+)/',
$foo,
$splitInput
);
return array_combine(
$splitInput['key'] ?? [],
$splitInput['value'] ?? []
);
};
$input = "MSI: YES XPF: NO PKG TYPE: XYZ VENDOR: WXYZ USER CODE: AB APP NAME: ATBTOOL VERSION: 1.0 MEDIA ZIP FILE: \\123.456.78.9\Path\TO\MY\MSI\MSIHelpV1.0.zip INSTALL DIR: G:\MSI EXISTING: NO";
echo json_encode(
parseFoo($input)
);
I know this has been discussed a lot here, but I still don't seem able to find aworking solution. Either it's out of date, it's the wrong programming-language or it's no longer supported.
All I want to do is: Get the last 'n' tweets from a public Twitter profile using PHP/JavaScript.
What API should I use best?
How do I keep it as lightweight as possible?
I can't use Node. js
I tried this, but I can't seem to get it to work, as simple as it may look like.
Simplest PHP example for retrieving user_timeline with Twitter API version 1.1
I've already registered for a developer account and created a "Twitter-App".
You can use this API, which I have used once and it works perfectly.
Download the file TwitterApiExchange.php from the repository above and you may use the following sample code to fetch tweets of a user:
<?php
echo '<pre>';
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$user = "rootcss";
$count = 100;
if (isset($_GET['user'])) {
$user = $_GET['user'];
}
if (isset($_GET['count'])) {
$count = $_GET['count'];
}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)->buildOauth($url, $requestMethod)->performRequest(), $assoc = TRUE);
if (isset($string["errors"][0]["message"])) {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>" . $string['errors'][0]["message"] . "</em></p>";
exit();
}
foreach ($string as $items) {
echo "Time and Date of Tweet: " . $items['created_at'] . "<br />";
echo "Tweet: " . $items['text'] . "<br />";
echo "Tweeted by: " . $items['user']['name'] . "<br />";
echo "Screen name: " . $items['user']['screen_name'] . "<br />";
echo "Followers: " . $items['user']['followers_count'] . "<br />";
echo "Friends: " . $items['user']['friends_count'] . "<br />";
echo "Listed: " . $items['user']['listed_count'] . "<br /><hr />";
}
echo '</pre>';
?>
It worked perfectly for me, Let me know if you face any issues.
I'm working on json source from wunderground.com. As the example code displayed in the document. I can adjust and work out for some simple format. But I'm stuck with this one. I tried to googled every where but there's no solution.
Here's the sample codes:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
Well, I need some information like "Cedar Rapids" out of pws/station :
"pws": {
"station": [
{
"neighborhood":"Ellis Park Time Check",
"city":"Cedar Rapids",
"state":"IA",
"country":"US",
"id":"KIACEDAR22",
"lat":41.981174,
"lon":-91.682632,
"distance_km":2,
"distance_mi":1
}
]
}
(You can get all code by clicking this : http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json )
Now the questions are:
What is this data called? (array, array in array?)
How could I pull this data out of the line?
Regards,
station is an array within the pws object.
To get the data, you can do something like this:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/b8e924a8f008b81e/geolookup/conditions/q/IA/Cedar_Rapids.json");
$parsed_json = json_decode($json_string);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (strcmp($station->{'id'}, "KIACEDAR22") == 0)
{
echo "Neighborhood: " . $station->{'neighborhood'} . "\n";
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
break;
}
}
?>
Output:
Current temperature in Cedar Rapids is: 38.5
Neighborhood: Ellis Park Time Check
City: Cedar Rapids
State: IA
Latitude: 41.981174
Longitude: -91.682632
Wonder if you can help for Christmas.
I am trying to read an XML but am having a few issues, basically the foreach structure isnt letting me return the data in the structure I want, and I am not sure of the correct way of doing this. Example below:
`<event id="298640100" date="Sat Dec 31 16:00:00 CET 2011">
<market id="9064667" type="1" status="Open" period="FT">
<description>Match Betting</description>
<place_terms>Win only</place_terms>
−
<outcome id="6798861400">
<description>Draw</description>
−
<price id="24532283602">
<decimal>3.5</decimal>
<fractional>5/2</fractional>
</price>
<position>2</position>
</outcome>
−
<outcome id="6798861200">
<description>Bolton Wanderers</description>
−
<price id="24532283402">
<decimal>2.0</decimal>
<fractional>1/1</fractional>
</price>
<position>1</position>
</outcome>
−
<outcome id="6798861300">
<description>Wolves</description>
−
<price id="24532283502">
<decimal>3.6</decimal>
<fractional>13/5</fractional>
</price>
<position>3</position>
</outcome>
</market>
</event>`
PHP
`<?php
$source = file_get_contents("vc.xml");
$xml = simplexml_load_string($source);
$game = $xml->xpath("//event");
foreach ($game as $event)
{
echo "<b>Event ID:</b> " . $event['id'] . "<br />";
echo "<b>Event Date:</b> " . $event['date'] . "<br />";
{
foreach ($event->children() as $market)
{
if ($market['period'] == 'FT')
{
foreach ($market->children() as $outcome)
{
echo "<b>Outcome ID:</b> " . $outcome['id'] . "<br />";
foreach ($outcome->children() as $price)
{
echo "<b>Price ID:</b> " . $price ['id'] . "<br />";
foreach ($price->children() as $value)
{
echo "<b>Value:</b> " . $value . "<br />";
}
}
}
}
}
}
echo "<br />";
}
?>`
This is basically returning this:
Event ID: 298640100
Event Date: Sat Dec 31 16:00:00 CET 2011
Outcome ID:
Outcome ID:
Outcome ID: 6798861400
Price ID:
Price ID: 24532283602
Value: 3.5
Value: 5/2
Price ID:
Outcome ID: 6798861200
Price ID:
Price ID: 24532283402
Value: 2.0
Value: 1/1
Price ID:
Outcome ID: 6798861300
Price ID:
Price ID: 24532283502
Value: 3.6
Value: 13/5
Price ID:
Ideally I just want to return the following:
Event ID: 298640100
Event Date: Sat Dec 31 16:00:00 CET 2011
Outcome ID: 6798861400
Price ID: 24532283602
Value: 5/2
Any ideas what I am doing wrong and how I could achieve this.
Thanks in advance
Richard
You have 2 problems here. First, you are using the children() function, which returns all children, not just the specific type you want. This is why you get Outcome ID: 3 times in the begining. Instead of foreach ($market->children() as $outcome) you should use foreach ($market->outcome as $outcome).
Second, it seems like you only want the first result. In that case, you shouldn't be using a foreach. the simplexml object is a set of arrays, and you can access an inividual object in the array by its index number. You can get rid of a lot of your code and just grab the first outcome object directly like this:
$xml->event->market->outcome[0]
You might want to read the official simpleXML documentation http://www.php.net/manual/en/simplexml.examples-basic.php
Here is what i think you need:
foreach ($game as $event)
{
echo "<b>Event ID:</b> " . $event['id'] . "<br />";
echo "<b>Event Date:</b> " . $event['date'] . "<br />";
{
foreach ($event->children() as $market)
{
if ($market['period'] == 'FT')
{
foreach ($market->children() as $name => $outcome )
{
if ( $name != "outcome" )
{
continue;
}
echo "<b>Outcome ID: - $name</b> " . $outcome['id'] . "<br />";
foreach ($outcome->children() as $name => $price)
{
if ( $name != "price" )
{
continue;
}
echo "<b>Price ID:</b> " . $price ['id'] . "<br />";
foreach ($price->children() as $name => $value)
{
if ( $name != "fractional" )
{
continue;
}
echo "<b>Value: - $name</b> " . $value . "<br />";
break;
}
}
break;
}
break;
}
}
}
echo "<br />";
}