PHP, XML element path - php

Hey I am trying to get viewers from XML file. Problem is in path cuz other paths were working for me. I guess problem is because it's element? <media:statistics views="131"/>
$url = "https://www.youtube.com/feeds/videos.xml?channel_id=UCH7Hj6l_xDmbyvjQOA5Du0g";
$xml = simplexml_load_file($url);
$views = $xml->entry[0]->children('media', true)->group[0]->children('media', true)->community[0]->children('media', true)->attributes('statistics');
echo $views;

You could get the views by using instead of using ->attributes('statistics') use the statistics property first, and from that, get the views from the attributes:
->statistics->attributes()->views;
The code could look like:
$url = "https://www.youtube.com/feeds/videos.xml?channel_id=UCH7Hj6l_xDmbyvjQOA5Du0g";
$xml = simplexml_load_file($url);
$views = $xml->entry[0]->children('media', true)->group[0]->children('media', true)->community[0]->children('media', true)->statistics->attributes()->views;
echo $views;
Output
131

Related

PHP, Convert iTunes RSS to JSON

I am trying to utilize simplexml to convert an iTunes RSS Feed to JSON so I can better parse it. The issue I am having is that it is not coming back as correctly formatted JSON.
$feed_url = 'https://podcasts.subsplash.com/c2yjpyh/podcast.rss';
$feed_contents = file_get_contents($feed_url);
$xml = simplexml_load_string($feed_contents);
$podcasts = json_decode(json_encode($xml));
print_r($podcasts);
Is there a better way to be attempting this to get the correct result?
Thanks to IMSoP for pointing me in the right direction! This took a bit of studying but the solution ends up being very simple! Instead of trying to convert to a JSON format, just use SimpleXML. However, due to the namespaces, it does require an additional line to map the itunes: prefix.
So in my iTunes feed rss, the following line exists: xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd So we just reference this to make accessing the values very easy. Here is a quick example:
$rss = simplexml_load_file('https://podcasts.example.com/podcast.rss');
foreach ($rss->channel->item as $item){
// Now we define the map for the itunes: namespace
$itunes = $item->children('http://www.itunes.com/dtds/podcast-1.0.dtd');
// This is a value WITHOUT the itunes: namespace
$title = $item->title;
// This is a value WITH the itunes: namespace
$author = $itunes->author;
echo $title . '<br>';
echo $author . '<br>';
}
The other little issue that I ran into is getting attributes such as the url for images and audio links. That is accomplished by using the attributes() function like so:
// Access attributes WITH itunes: namespace
$image = $itunes->image->attributes();
// Access attributes WITHOUT itunes: namespace
$audio = $item->enclosure->attributes();
// To echo these we simple add the desired attribute in `[]`:
echo $image['href'] . '<br>';
echo $audio['url'] . '<br>';

getting xml from URL into variable

I am trying to get an xml feed from a url
http://api.eve-central.com/api/marketstat?typeid=1230&regionlimit=10000002
but seem to be failing miserably. I have tried
new SimpleXMLElement,
file_get_contents and
http_get
Yet none of these seem to echo a nice XML feed when I either echo or print_r. The end goal is to eventually parse this data but getting it into a variable would sure be a nice start.
I have attached my code below. This is contained within a loop and $typeID does in fact give the correct ID as seen above
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
echo $url."<br />";
$xml = new SimpleXMLElement($url);
print_r($xml);
I should state that the other strange thing I am seeing is that when I echo $url, i get
http://api.eve-central.com/api/marketstat?typeid=1230®ionlimit=10000002
the &reg is the registered trademark symbol. I am unsure if this is "feature" in my browser, or a "feature" in my code
Try the following:
<?php
$typeID = 1230;
// set feed URL
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
echo $url."<br />";
// read feed into SimpleXML object
$sxml = simplexml_load_file($url);
// then you can do
var_dump($sxml);
// And now you'll be able to call `$sxml->marketstat->type->buy->volume` as well as other properties.
echo $sxml->marketstat->type->buy->volume;
// And if you want to fetch multiple IDs:
foreach($sxml->marketstat->type as $type){
echo $type->buy->volume . "<br>";
}
?>
You need to fetch the data from the URL in order to make an XML object.
$url = 'http://api.eve-central.com/api/marketstat?typeid='.$typeID.'&regionlimit=10000002';
$xml = new SimpleXMLElement(file_get_contents($url));
// pre tags to format nicely
echo '<pre>';
print_r($xml);
echo '</pre>';

Loading Multiple XML feeds - PHP

I have a php file setup to pull through ONE XML data feed, What I would like to do is load up to 4 feeds into it and if possible make it select a random item too. Then parse that into an jQuery News Ticker.
My current PHP is as follows...
<?php
$feed = new DOMDocument();
$feed->load('/feed');
$json = array();
$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $item) {
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
$json['item'][$i++]['title'] = $title;
$json['item'][$i++]['description'] = $description;
$json['item'][$i++]['pubdate'] = $pubDate;
$json['item'][$i++]['guid'] = $guid;
echo '<li class="news-item">'.$title.'</li>';
}
//echo json_encode($json);
?>
How can I modify this to load more than one feed into the file?
Thanks in advance
The simplest approach to doing this is wrapping another loop around the code you have. It's not the cleanest way but will probably suffice for the purpose.
In general, IMO, it's always beneficial to learn the basics of the language first. E.g. PHP manual on foreach
This is roughly what the loop needs to look like:
$my_feeds = array("http://.....", "http://.....", "http://.....");
foreach ($my_feeds as $my_feed)
{
// This is where your code starts
$feed = new DOMDocument();
$feed->load($my_feed); <--------------- notice the variable
$json = array();
... and the rest of the code
}
this will walk through all the URLs in $my_feeds, open the RSS source, fetch all the items from it, and output them.
If I'm reading your question right, what you may want to do is turn your code into a function, which you would then run inside a foreach loop for each url (which you could store in an array or other data structure).
Edit: If you don't know much about functions, this tutorial section might help you. http://devzone.zend.com/9/php-101-part-6-functionally-yours/

Read an XML style file using PHP

I am trying to retrieve data from this XML style file :
<Product_Group>
<Product_Group_ID>131</Product_Group_ID>
<Product_Group_Title>Thanks for the Memories</Product_Group_Title>
<Products>
<On_Sale_Date>03/01/12 00:00:00.000</On_Sale_Date>
<ISBN>9780007233694</ISBN>
<Title>Thanks for the Memories</Title>
<Format>Paperback</Format>
<Sub_Format/>
<CoverImageURL_Small>http://www.harpercollins.com/harperimages/isbn/small/4/9780007233694.jpg</CoverImageURL_Small>
</Products>
</Product_Group>
I am using following code but this seems to retrieve nothing. any help in fixing this issues would be highly appreciated
$xml = simplexml_load_string($response);
//$xml= $response;
$updates = array();
//loop through all the entry(s) in the feed
for ($i=0; $i<count($xml->Product_Group); $i++)
{
//get the id from entry
$ISBN = $xml->entry[$i]->ISBN;
//get the account link
$Title = $xml->entry[$i]->Title;
//get the tweet
$Product_Group_SEO_Copy = $xml->entry[$i]->Product_Group_SEO_Copy;
}
1) It is not valid XML. What warnings do you see? You'll need to fix them for simplexml_load_string to work properly.
For example, </CoverImageURL_Small> should be <CoverImageURL_Small/>
2) Assuming that Product_Group is not your actual document root (if it is than $xml points to it already and $xml->Product_Group will not work) then you can access each element like
$xml->Product_Group->Products[$i]->ISBN;
3) It's usually simpler to use a foreach loop than a for loop when dealing with simplexml
foreach($xml->Product_Group->Products as $p)
{
$ISBN = $p->ISBN;
//var_dump($ISBN);
}

PHP Retrieve DATA from XML

My first attempt at retrieving data from XML for a maps application has failed. Here is a piece of the XML Feed.
<?xml version="1.0" encoding="UTF-8"?>
<DirectionsResponse>
<status>OK</status>
<route>
<leg>
<start_address>Winkfield, Bracknell, Berkshire RG42 6LY, UK</start_address>
<end_address>Wentworth, Surrey GU25 4, UK</end_address>
</leg>
</route>
</DirectionsResponse>
I want to get the start and end address and return them via AJAX to the application.
The PHP
<?php
$start = $_POST['start'];
$end = $_POST['end'];
$xml = simplexml_load_file('http://maps.googleapis.com/maps/api/directions/xml?origin='.$start.'&destination='.$end.'&sensor=false');
// data to fetch
$start = $xml->xpath("/DirectionsResponse/route/leg/start_address");
$end = $xml->xpath("/DirectionsResponse/route/leg/end_address");
$start = array($start);
// output
echo json_encode( array('output'=>$start[0]));
?>
Annoyingly this is returning an object to the page.
Response :: {"output":[{"0":"Winkfield, Windsor, Berkshire SL4 2ES, UK"}]}
Anyone know how to stop that from happening. I just want the value Winkfield, Windsor, Berkshire SL4 2ES, UK.
Haven't tested your specific case, but i remember running into something similar when using SimpleXML, you might want to use (string) to cast it out of the object
array('output'=> (string)$start[0])
Or rather just leave out $start = array($start) and just do
array('output'=> (string)$start)
On reading the SimpleXML XPath documentation (http://www.php.net/manual/en/simplexmlelement.xpath.php) again i think your problem might be this:
Returns an array of SimpleXMLElement objects or FALSE in case of an error.
So the XPath returns an array, then you wrap that in an array and take the first element of that array, so all you end up with is the original array - remove the array wrap and you should be fine
function XMLReader()
{
$MyArray = array();
$doc = new DOMDocument();
$doc->load( 'XMLFilePath.xml' );
$info = $doc->getElementsByTagName( "leg" );
foreach( $info as $Type )
{
$details = $Type->getElementsByTagName( "start_address" );
$detail = $details->item(0)->nodeValue;
$MyArray [] = $detail;
}
return $MyArray;
}
and same for end_Address.
I wish this answer is helpful.
Just echo $start? Also, why do you make an array of start and then output the first element, it doesnt make any sense at all.
echo $xml->route->leg->start_address;
This is the edited answer. I checked it. Its working properly on the XML.

Categories