how to retrieve both instances of element in an xml file
here is how i have been getting the others
$LargeImage = $xml->Items->Item->LargeImage->URL;
$author = $xml->Items->Item->ItemAttributes->Author;
echo ($author);
however for $author, there are 2 authors and the element is like this
Items->Item->ItemAttributes->
<Author>Ralph Bravaco</Author>
<Author>Shai Simonson</Author>
so my current code is only able to get back the first author
Try this:
foreach($xml->Items->Item->ItemAttributes->Author as $author) {
echo (string)$author.'<br>';
}
It will echo all authors irrespective of no. of authors.
$xml = new SimpleXMLElement($string);
$result = $xml->xpath('/Items/Item/ItemAttributes/Author');
while(list( , $node) = each($result)) {
echo $node,"\n";
}
I think you are asking for this --
echo $author = $xml->Items->Item->ItemAttributes->Author[0];
echo $author = $xml->Items->Item->ItemAttributes->Author[1];
Related
I have such php code:
$xml = #simplexml_load_file('2.xml', 'SimpleXMLElement',LIBXML_NOCDATA);
print_r($xml);
How to get values of:
DialingNumber,StartTime,AnswerTime ?
foreach ($xml as $show)
{
echo (string)$show['DialedNumber'];
echo (string)$show['AnswerNumber'];
echo (string)$show['WaitDuration'];
}
NOT WORKING ! How to get values of: DialingNumber,StartTime,AnswerTime ?
There are problems with the the XML file itself, which can be 'corrected' with just replacing some of the entities with some dummy data. The second part is to reference the correct path to the data you want to output.
$filename = '2.xml';
$data = file_get_contents($filename);
$data = str_replace(["&rs", "&rc"], "", $data); // Remove entity references
$xml = simplexml_load_string($data);
foreach ($xml->Tablix1->DialedNumber_Collection->DialedNumber->Details_Collection->Details
as $details)
{
echo (string)$details['DialedNumbers'].PHP_EOL;
echo (string)$details['AnswerNumber'].PHP_EOL;
echo (string)$details['WaitDuration'].PHP_EOL;
}
Can you try as below?
foreach ($xml as $show)
{
echo (string)$show[0]['DialedNumber'];
echo (string)$show[0]['AnswerNumber'];
echo (string)$show[0]['WaitDuration'];
}
I am somewhat new with PHP, but can't really wrap my head around what I am doing wrong here given my situation.
Problem: I am trying to get the href of a certain HTML element within a string of characters inside an XML object/element via Reddit (if you visit this page, it would be the actual link of the video - not the reddit link but the external youtube link or whatever - nothing else).
Here is my code so far (code updated):
Update: Loop-mania! Got all of the hrefs, but am now trying to store them inside a global array to access a random one outside of this function.
function getXMLFeed() {
echo "<h2>Reddit Items</h2><hr><br><br>";
//$feedURL = file_get_contents('https://www.reddit.com/r/videos/.xml?limit=200');
$feedURL = 'https://www.reddit.com/r/videos/.xml?limit=200';
$xml = simplexml_load_file($feedURL);
//define each xml entry from reddit as an item
foreach ($xml -> entry as $item ) {
foreach ($item -> content as $content) {
$newContent = (string)$content;
$html = str_get_html($newContent);
foreach($html->find('table') as $table) {
$links = $table->find('span', '0');
//echo $links;
foreach($links->find('a') as $link) {
echo $link->href;
}
}
}
}
}
XML Code:
http://pasted.co/0bcf49e8
I've also included JSON if it can be done this way; I just preferred XML:
http://pasted.co/f02180db
That is pretty much all of the code. Though, here is another piece I tried to use with DOMDocument (scrapped it).
foreach ($item -> content as $content) {
$dom = new DOMDocument();
$dom -> loadHTML($content);
$xpath = new DOMXPath($dom);
$classname = "/html/body/table[1]/tbody/tr/td[2]/span[1]/a";
foreach ($dom->getElementsByTagName('table') as $node) {
echo $dom->saveHtml($node), PHP_EOL;
//$originalURL = $node->getAttribute('href');
}
//$html = $dom->saveHTML();
}
I can parse the table fine, but when it comes to getting certain element's values (nothing has an ID or class), I can only seem to get ALL anchor tags or ALL table rows, etc.
Can anyone point me in the right direction? Let me know if there is anything else I can add here. Thanks!
Added HTML:
I am specifically trying to extract <span>[link]</span> from each table/item.
http://pastebin.com/QXa2i6qz
The following code can extract you all the youtube links from each content.
function extract_youtube_link($xml) {
$entries = $xml['entry'];
$videos = [];
foreach($entries as $entry) {
$content = html_entity_decode($entry['content']);
preg_match_all('/<span><a href="(.*)">\[link\]/', $content, $matches);
if(!empty($matches[1][0])) {
$videos[] = array(
'entry_title' => $entry['title'],
'author' => preg_replace('/\/(.*)\//', '', $entry['author']['name']),
'author_reddit_url' => $entry['author']['uri'],
'video_url' => $matches[1][0]
);
}
}
return $videos;
}
$xml = simplexml_load_file('reddit.xml');
$xml = json_decode(json_encode($xml), true);
$videos = extract_youtube_link($xml);
foreach($videos as $video) {
echo "<p>Entry Title: {$video['entry_title']}</p>";
echo "<p>Author: {$video['author']}</p>";
echo "<p>Author URL: {$video['author_reddit_url']}</p>";
echo "<p>Video URL: {$video['video_url']}</p>";
echo "<br><br>";
}
The code outputs in the multidimensional format of array with the elements inside are entry_title, author, author_reddit_url and video_url. Hope it helps you!
If you're looking for a specific element you don't need to parse the whole thing. One way of doing it could be to use the DOMXPath class and query directly the xml. The documentation should guide you through.
http://php.net/manual/es/class.domxpath.php .
I am using the below code to fetch the $movie->id from the response XML
<?php
$movie_name='Dabangg 2';
$url ='http://api.themoviedb.org/2.1/Movie.search/en/xml/accd3ddbbae37c0315fb5c8e19b815a5/%22Dabangg%202%22';
$xml = simplexml_load_file($url);
$movies = $xml->movies->movie;
foreach ($movies as $movie){
$arrMovie_id = $movie->id;
}
?>
the response xml structure is
How to fetch image URL with thumb size?
See the below an easy way to get only specific images.
$xml = simplexml_load_file($url);
$images = $xml->xpath("//image");
//echo "<pre>";print_r($images);die;
foreach ($images as $image){
if($image['size'] == "thumb"){
echo "URL:".$image['url']."<br/>";
echo "SIZE:".$image['size']."<br/>";
echo "<hr/>";
}
}
Use the attributes() method of SimpleXmlElement.
Example:
$imageAttributes = $movie->images[0]->attributes();
$size = $imageAttributes['size'];
See the documentation at: http://www.php.net/manual/en/simplexmlelement.attributes.php
EDIT: select only URL attributes with size = "thumb" and type = "poster":
$urls = $xml->xpath("//image[#size='thumb' and #type='poster']/#url");
if you expect only 1 url, do:
$url = (string)$xml->xpath("//image[#size='thumb' and #type='poster']/#url")[0];
echo $url;
working live demo: http://codepad.viper-7.com/wdmEay
I am using a formbuilder plugin in Wordpress which submits the form input to the database as XML data. Now I would like to fetch that data and have it displayed in another page. I have started trying simpleXML to achieve this but now I have hit a road bump.
The XML data that appears in each row of the database follows this format:
<form>
<FormSubject>Report</FormSubject>
<FormRecipient>****#***.com</FormRecipient>
<Name>admin</Name>
<Department>test</Department>
<Value>1000</Value>
<Comments>test</Comments>
<Page>http://***.com</Page>
<Referrer>http://****.com</Referrer>
</form>
I have previously managed to fetch the data that I need using simpleXML from an XML string of the same markup which is in the database but now my question is, how do I do this with a loop for each row in the database?
When the following code is run, wordpress displays a blank page meaning that there is an error:
<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$string = $statistic->xmldata
$xml = simplexml_load_string($string);
$Name = (string) $xml->Name;
$Department = (string) $xml->Department;
$Value = (string) $xml->Value;
$Comments = (string) $xml->Comments;
echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";
?>
You are missing ; on line 5
$string = $statistic->xmldata
Should be
$string = $statistic->xmldata;
You should consider enablign WP_DEBUG constant in wp-config.php file. Insert following code to your wp-config.php, just before /* That's all, stop editing! Happy blogging. */
define('WP_DEBUG', true);
/* That's all, stop editing! Happy blogging. */
For more tips on debugging, read the codex
Formbuilder users custom function to extract XML data in formbuilder_xml_db_results Class:
function xmltoarray($xml)
{
$xml = trim($xml);
$match = "#<([a-z0-9_]+)([ \"']*[a-z0-9_ \"']*)>(.*)(</\\1>)#si";
$offset = 0;
if(!preg_match($match, $xml, $regs, false, $offset)) {
return($xml);
}
while(preg_match($match, $xml, $regs, false, $offset))
{
list($data, $element, $attribs, $content, $closing) = $regs;
$offset = strpos($xml, $data) + strlen($data);
$tmp = $this->xmltoarray($content);
$result[$element] = $tmp;
}
return($result);
}
Define that function in your code (before global $wpdb; you don't have to be afraid of same name as that function is defined in Class) and than modify your code in this way:
<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$xml = xmltoarray( $statistic->xmldata );
$Name = (string) $xml['form']['Name'];
$Department = (string) $xml['form']['Department'];
$Value = (string) $xml['form']['Value'];
$Comments = (string) $xml['form']['Comments'];
echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT: edited $xml['Comments'] to $xml['form']['Comments'] and analogous
I fixed it by stripping the backslashes from the XML string using stripslashes()
I'm trying to get the entry->id and entry->cap:parameter->value for every entry in the RSS feed.... below is the code I'm using. It is displaying the id correctly however it is not displaying the value field.... please help.
$url = 'http://alerts.weather.gov/cap/us.php?x=1';
$cap = simplexml_load_file($url);
foreach($cap->entry as $entry){
echo 'ID: ', $entry->id, "\n";
echo 'VTEC: ', $entry->children('cap', true)->parameter->value, "\n";
echo "<hr>";
}
Thanks for the help in advance.
The <value> element is not in the same namespace as <cap:parameter>:
<cap:parameter>
<valueName>VTEC</valueName>
<value>/O.CON.KMPX.FL.W.0012.000000T0000Z-110517T1800Z/</value>
</cap:parameter>
So you have to call children() again.
Code (demo)
$feed = simplexml_load_file('http://alerts.weather.gov/cap/us.php?x=1');
foreach ($feed->entry as $entry){
printf(
"ID: %s\nVTEC: %s\n<hr>",
$entry->id,
$entry->children('cap', true)->parameter->children()->value
);
}