-4

I want to get a Media:description from NYT external (RSS) XML file.

The following code works:

<?php
$url = "http://rss.nytimes.com/services/xml/rss/nyt/Sports.xml"; // xmld.xml contains above data
$feeds = file_get_contents($url);
$rss = simplexml_load_string($feeds);
$items = [];
foreach($rss->channel->item as $entry) {
    $image = '';
    $image = 'N/A';
    foreach ($entry->children('media', true) as $k => $v) {
        $attributes = $v->attributes();
            if (count($attributes) == 0) {
            continue;
        } else {
            $image = $attributes->url;
        }
    }

    $items[] = [
        'link' => $entry->link,
        'title' => $entry->title,
        'image' => $image,
    ];

}

//print_r($items);

foreach ($items as $item) {
    printf('<img src="%s">', $item['image']);
    printf('<a href="%s">%s</a>', $item['link'], $item['title']);
}
?>

This results in:

image and text

How can I continue?

Also I kind of know to get description with another method. But using two methods I will not keep the (item)description in the same Array. Code to extract description could be:

Following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>How to Parse XML with SimpleXML and PHP</title>
</head>
<body>
<?php
$url = 'http://rss.nytimes.com/services/xml/rss/nyt/Sports.xml';
$xml = simplexml_load_file($url) or die("Can't connect to URL");

?><pre><?php //print_r($xml); ?></pre><?php

foreach ($xml->channel->item as $item) {
    printf('<li><a href="%s">%s</a></li><br>%s', $item->link, $item->title, $item->description);
}
?>  
</body>
</html>

RESULT IN:

Link and Description but no image - as simplexml_load_file doesn't handle media tags

-- Edit 2:

Just was thinking about limit barrier too. And I know this code works :

<?php

$rss = new DOMDocument();
$rss->load('http://careers.pageuppeople.com/671/cw/en-us/rss');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
                $item = array ( 
                                'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                                'desc' => $node->getElementsByTagNameNS("http://pageuppeople.com/","description")->item(0)->nodeValue,
                                'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
                                'pubDate' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
                                'closeDate' => $node->getElementsByTagName('closingDate')->item(0)->nodeValue,
                                'field_city' => $node->getElementsByTagName('location')->item(0)->nodeValue,
                                );
                array_push($feed, $item);
}
$limit = 50;
echo '<?xml/>';
for($x=0;$x<$limit;$x++) {
                echo '<item>';
                $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
                $link = $feed[$x]['link'];
                $description = $feed[$x]['desc'];
                $field_city = $feed[$x]['field_city'];
                $pubDate = date('Y: m: d', strtotime($feed[$x]['pubDate']));
                $closeDate = date('Y: m: d', strtotime($feed[$x]['closeDate']));
                echo '<title>'.$title.'</title>';
                echo '<pubDate>'.$pubDate.'</pubDate>';
                echo '<closeDate> '.$closeDate.'</closeDate>';
                echo '<link>'.$link.'</link>';
                echo '<field_city>'.$field_city.'</field_city>';
                echo '<body>'.$description.'</body>';
                echo '<field_how_to_apply><strong>UNICEF is committed to diversity and inclusion within its workforce, and encourages qualified female and male candidates from all national, religious and ethnic backgrounds, including persons living with disabilities, to apply to become a part of our organization.<br><br>To apply click on the link below.</strong><br><br>'.$link.'</field_how_to_apply>';
                echo '</item>';

}

echo '</channel></rss>';

?>

But I don't know really how to use it in my current method.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    Can you specifically tell what is the error you are getting? – MD. Atiqur Rahman Apr 17 '17 at 10:19
  • No errors. Im just not clear how to reach using rss parse simplexml from http://rss.nytimes.com/services/xml/rss/nyt/Sports.xml A friend of mine helped me reach and only get the image link and print it as an image. (code in question) –  Apr 17 '17 at 10:23
  • 2
    Hi Stephanie. This looks like the beginnings of a good question, but it is so chatty it may confuse readers, and confusing questions are in danger of closure. Who is "this nice guy"? What is "almost done"? Who is the "Gentleman"? I guess that this is spill-over from a previous question, but it is best not to do that - please ask each question as if it were your only question on the site, and remember your readers are likely to be different each time. – halfer Apr 18 '17 at 13:59
  • If you would like to refer to a previous question, then you'll need to state it explicitly: "I asked this question here [add link] but am having trouble foobarring the widget". That gives your readers some essential context to work with. – halfer Apr 18 '17 at 14:01
  • OK, I have trimmed the chatty material that assumed too much context from elsewhere. It is a bit more understandable now, I think. For your first image, what is wrong there that you want to help with? You've said this code is working. – halfer Apr 18 '17 at 14:07

2 Answers2

1

Try the below code in the loop,

$description = $entry->children('media', true)->description;

Full Code,

foreach($rss->channel->item as $entry) {
    $image = '';
    $image = 'N/A';
    foreach ($entry->children('media', true) as $k => $v) {
        $attributes = $v->attributes();
            if (count($attributes) == 0) {
            continue;
        } else {
            $image = $attributes->url;
        }
    }
    $items[] = [
        'link' => $entry->link,'title' => $entry->title,
        'image' => $image,'description'=>$entry->children('media', true)->description
    ];
}

foreach ($items as $item) {
    printf('<img src="%s">', $item['image']);
    printf('<a href="%s">%s</a>', $item['link'], $item['title']);
    echo '<p>'.$item['description'].'</p>';
}

PHPFiddle

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • 1
    As a developer a small hint is more than enough, but Navjot had just copied all code once again nad it will help you then its Ok. But one more thing I want to say in Navjot's answer, don't assign description again and again in loop, for this you can check my answer, I've just assign description only once and outside the loop. By the way a demo can help you on http://phpfiddle.org/main/code/djwy-kxim – Rohan Kumar Apr 17 '17 at 11:05
  • First of all. Thank you for giving me and my question attention and help =). I also happy you made me found phpfiddle. i knew about jsfiddle but never know php fiddle existed too. =) . Also I tried to copy the code in phpfiddle removing the XML (part) . starting with ` –  Apr 17 '17 at 11:12
  • Warning: simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found in C:\xampp\htdocs\project\_new\nyt\wireframe\_test\simplexml\rohan.php on line 5 Warning: simplexml_load_string(): http://rss.nytimes.com/services/xml/rss/nyt/Sports.xml in C:\xampp\htdocs\project\_new\nyt\wireframe\_test\simplexml\rohan.php on line 5 –  Apr 17 '17 at 11:13
  • Im sure its my fault not Yours. Because running the code in PHPfiddle did work really well and your code doesn't have the description locked in the Array so that was really neat. the Warning message gave me -1 clue how to proceed to I love if you could help me get the code to work =) –  Apr 17 '17 at 11:14
1

You can get the description using $description = $entry->children('media', true)->description;

 <?php
    $url = "http://rss.nytimes.com/services/xml/rss/nyt/Sports.xml"; // xmld.xml contains above data
    $feeds = file_get_contents($url);
    $rss = simplexml_load_string($feeds);

    $items = [];

    foreach($rss->channel->item as $entry) {
        $image = '';
        $image = 'N/A';
        foreach ($entry->children('media', true) as $k => $v) {
            $attributes = $v->attributes();

            if (count($attributes) == 0) {
                continue;
            } else {
                $image = $attributes->url;
            }
        $content_data = (string)$entry->children("media", true)->description;
        }


        $items[] = [
            'link' => $entry->link,
            'title' => $entry->title,
            'image' => $image,
            'Desc' =>$content_data,

        ];

    }

    //print_r($items);

       $i=0; 
foreach ($items as $item) {
 if ($i < 3) {

  printf('<img src="%s">', $item['image']);
  printf('<a href="%s">%s</a>', $item['link'], $item['title']); printf('<p>%s</p>', $item['Desc']);
   $i++; 

  } 
  } 
    ?>
  • Can I ask one more thing. I wrote this code into it too.. `$credit = (string)$entry->children("media", true)->credit;` and `'credit' =>$credit,` and `printf('

    credit to: %s

    ', $item['credit']);` . resulted in: Pete Kiehart for The New York Times . But I only want Pete Kiehart.. Do I do some kind of string transform?
    –  Apr 17 '17 at 10:53
  • 1
    Yes you can do replace the string but its not a good idea. because this is for some values not for all –  Apr 17 '17 at 11:03
  • Well you can take the first word of a string . http://stackoverflow.com/questions/2476789/how-to-get-the-first-word-of-a-sentence-in-php using `$myvalue = 'Test me more'; $arr = explode(' ',trim($myvalue)); echo $arr[0]; // will print Test` But I would love if someone could provide either 1. get second and third words as well... 2. select words based on their position in the String. Like.. "I am sitting here and its raining" into " I am sitting and raining" - –  Apr 17 '17 at 11:15
  • Find one solution = `` from http://stackoverflow.com/questions/13263523/getting-first-two-words-from-string-in-php –  Apr 17 '17 at 11:27
  • Dont know how to use it though.. I think i got some kind of array to string error. So i should use implode.. but how? :D https://www.w3schools.com/php/func_string_implode.asp –  Apr 17 '17 at 11:37