Срезать изображение строки src с помощью PHP - PullRequest
0 голосов
/ 29 апреля 2019

Я пытаюсь получить изображение src из Atom Feed на основе XML, используя PHP. Я хочу сделать это, разрезав строку в фиде так, чтобы захватывался только URL.

До сих пор я мог использовать команду substr() для нарезания определенной длины строки. Проблема заключается в том, что длина URL-адреса изображения в канале будет часто варьироваться, поэтому мне нужно нарезать фрагмент на основе определенного символа.

Я попытался использовать Explode, чтобы указать символ для нарезки:

foreach ($array['entry'] as $post) {
            if ($current > $max) break;
            $posts[] = [
            'post_img' => explode("\"", $post['content'], 2),

... но это не сработало. Вот код XML, из которого я пытаюсь получить:

<content type="html">&lt;img alt="" class="attachment image image" src="http://awpagesociety.com/attachments/20aa91b841d6a49dd945a97af37509add2680573/store/limit/452/300/e6941ac426f6cbca5774cad6f2e8b6447c96d92d32957be6709dac201de7/Brady-Bush.jpg" 

А вот и метод в полном объеме. Поля url, post_content и post_title назначаются правильно:

    $feed = getRssFile();
    if ($feed == false) return;
    $xml = simplexml_load_file($feed);
    $json = json_encode($xml);
    $array = json_decode($json,TRUE);
    $posts = [];
    if (count($array['entry'])) {
        $max = 3;
        $current = 1;
        foreach ($array['entry'] as $post) {
            if ($current > $max) break;
            $posts[] = [
            'post_img' => explode("src=", $post['content'], //isn't working
            'post_title' => $post['title'],
                'post_content' => substr(sanitizeContent($post['content']), 0, 200),
                'url' => $post['link']['@attributes']['href']
            ];
            $current++;
        }
    }
    return $posts;

}

explode () ничего не назначает полю src изображения, когда я проверяю в инспекторе элементов. Он просто говорит img src(unknown) Есть ли какие-нибудь альтернативы для получения нужного мне результата?

РЕДАКТИРОВАТЬ: вот что возвращается от выполнения

           $exp = explode("src=", $thing);
            var_dump($exp[1]);
            var_dump($exp);

Результат:

string(226) ""http://awpagesociety.com/attachments/c881c9ec924cfd1ee7f0650f2b6de9b36d4e31a9/store/limit/452/300/25f7a5696d2bd1d5e4d1137924ff04e3e2c8333fa8c71e005462a4e710d9/Walker_Recording.jpg" /><iframe style="border: none" " array(3) { [0]=> string(43) " string(226) ""http://awpagesociety.com/attachments/c881c9ec924cfd1ee7f0650f2b6de9b36d4e31a9/store/limit/452/300/25f7a5696d2bd1d5e4d1137924ff04e3e2c8333fa8c71e005462a4e710d9/Walker_Recording.jpg" /><iframe style="border: none" " [2]=> string(3454) ""//html5-player.libsyn.com/embed/episode/id/9576506/height/90/theme/custom/thumbnail/yes/direction/forward/render-playlist/no/custom-color/000000/" height="90" width="50%" scrolling="no" allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="" oallowfullscreen="" msallowfullscreen=""><span id="selection-marker-1" class="redactor-selection-marker"></span></iframe> <p><em><br></em></p> <p><em>If you’re interested in more conversations like this on The New CCO, subscribe on&nbsp;<span class="redactor-unlink"></span><span class="redactor-unlink"></span><a href="https://podcasts.apple.com/us/podcast/upskilling-a-workforce-reggie-walker-pwc/id1212422149?i=1000436862014" target="_blank">iTunes</a>,&nbsp;<span class="redactor-unlink"></span><a href="https://play.google.com/music/m/Dd6jidfd7eq4pzgwx7p3w6gigxm?t=Upskilling_a_Workforce_-_Reggie_Walker_PwC-The_New_CCO" target="_blank">Google Play</a>, or&nbsp;<span class="redactor-unlink"></span><span class="redactor-unlink"></span><a href="https://open.spotify.com/show/5oLW0nzEPyNo7mfcSFfIcu?si=gDn3b288RoiG8k9Xz9xH6g" target="_blank">Spotify</a>.</em></p> <p class="text-center">* * *</p> <p>Enterprises face severe disruption, whether via technology, business model, new competition, etc. In order to keep up, organizations must answer fundamental questions about the nature of their business, starting with their people. “What kind of culture do we need to compete in our industry? What does it look like, feel like, sound like? What are the base skills our people possess? Where do they come from?”&nbsp;</p> <p>These are some of the questions Reggie Walker, Chief Commercial Officer at PwC, has wrestled with while leading the enterprise's communications function over the past three years. He’s led a critical organization-wide effort around digital upskilling to better align PwC’s people with its business strategy. He’s also unified the Communications, Sales and Marketing functions, streamlining an operation that was once disparate entities.&nbsp;</p> <p>On this episode of The New CCO, we’ll learn more about each of these initiatives from Reggie and how they ladder up to a new kind of CCO role that’s swiftly changing in order to adapt to new disruptive factors.&nbsp;</p> <p>Here’s Reggie’s take on where he sees the future of work going over the next five years:</p> <p>“The opportunities are almost endless. We have to be responsible. And by that I mean there’s a lot of things we can do with technology. We have to make sure we’re not overextending the reach of certain technologies and cannibalizing jobs and opportunities. But, man, where will it not take us? That’s the fun part.”</p> <p><em>Do you have a story to tell? Share it with us. Please reach out to Justin Pallenik at <a href="mailto:jpallenik@page.org" target="_blank">jpallenik@page.org</a> with your CCO story.</em></p>" } string(3252) ""http://awpagesociety.com/attachments/20aa91b841d6a49dd945a97af37509add2680573/store/limit/452/300/e6941ac426f6cbca5774cad6f2e8b6447c96d92d32957be6709dac201de7/Brady-Bush.jpg" /><p>

И я хочу просто вернуть каждый источник изображения отдельно, например

"http://awpagesociety.com/attachments/c881c9ec924cfd1ee7f0650f2b6de9b36d4e31a9/store/limit/452/300/25f7a5696d2bd1d5e4d1137924ff04e3e2c8333fa8c71e005462a4e710d9/Walker_Recording.jpg", "http://awpagesociety.com/attachments/20aa91b841d6a49dd945a97af37509add2680573/store/limit/452/300/e6941ac426f6cbca5774cad6f2e8b6447c96d92d32957be6709dac201de7/Brady-Bush.jpg"

В основном хотят вырезать весь другой контент, например текст между тегами стиля и другим форматированием.

РЕДАКТИРОВАТЬ 2 Пример XML:

<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:page.org,2005:/blog</id>
  <link rel="alternate" type="text/html" href="https://page.org"/>
  <link rel="self" type="application/atom+xml" href="https://page.org/blog.atom"/>
  <title>Blog | Arthur W. Page Society</title>
  <updated>2019-04-29T16:00:00Z</updated>
  <entry>
    <id>tag:page.org,2005:BlogPost/29039</id>
    <published>2019-04-29T16:00:00Z</published>
    <updated>2019-04-30T15:52:28Z</updated>
    <link rel="alternate" type="text/html" href="https://page.org/blog/the-new-cco-podcast-upskilling-a-workforce-reggie-walker-pwc"/>
    <title>The New CCO Podcast: Upskilling a Workforce - Reggie Walker, PwC</title>
    <content type="html">&lt;img alt="" class="attachment image image" src="http://awpagesociety.com/attachments/c881c9ec924cfd1ee7f0650f2b6de9b36d4e31a9/store/limit/452/300/25f7a5696d2bd1d5e4d1137924ff04e3e2c8333fa8c71e005462a4e710d9/Walker_Recording.jpg" /&gt;&amp;lt;iframe style=&amp;quot;border: none&amp;quot; src=&amp;quot;//html5-player.libsyn.com/embed/episode/id/9576506/height/90/theme/custom/thumbnail/yes/direction/forward/render-playlist/no/custom-color/000000/&amp;quot; height=&amp;quot;90&amp;quot; width=&amp;quot;50%&amp;quot; scrolling=&amp;quot;no&amp;quot; allowfullscreen=&amp;quot;&amp;quot; webkitallowfullscreen=&amp;quot;&amp;quot; mozallowfullscreen=&amp;quot;&amp;quot; oallowfullscreen=&amp;quot;&amp;quot; msallowfullscreen=&amp;quot;&amp;quot;&amp;gt;&amp;lt;span id=&amp;quot;selection-marker-1&amp;quot; class=&amp;quot;redactor-selection-marker&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;&amp;lt;/iframe&amp;gt;
&amp;lt;p&amp;gt;&amp;lt;em&amp;gt;&amp;lt;br&amp;gt;&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;&amp;lt;em&amp;gt;If you’re interested in more conversations like this on The New CCO, subscribe on&amp;amp;nbsp;&amp;lt;span class=&amp;quot;redactor-unlink&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;&amp;lt;span class=&amp;quot;redactor-unlink&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;&amp;lt;a href=&amp;quot;https://podcasts.apple.com/us/podcast/upskilling-a-workforce-reggie-walker-pwc/id1212422149?i=1000436862014&amp;quot; target=&amp;quot;_blank&amp;quot;&amp;gt;iTunes&amp;lt;/a&amp;gt;,&amp;amp;nbsp;&amp;lt;span class=&amp;quot;redactor-unlink&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;&amp;lt;a href=&amp;quot;https://play.google.com/music/m/Dd6jidfd7eq4pzgwx7p3w6gigxm?t=Upskilling_a_Workforce_-_Reggie_Walker_PwC-The_New_CCO&amp;quot; target=&amp;quot;_blank&amp;quot;&amp;gt;Google Play&amp;lt;/a&amp;gt;, or&amp;amp;nbsp;&amp;lt;span class=&amp;quot;redactor-unlink&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;&amp;lt;span class=&amp;quot;redactor-unlink&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;&amp;lt;a href=&amp;quot;https://open.spotify.com/show/5oLW0nzEPyNo7mfcSFfIcu?si=gDn3b288RoiG8k9Xz9xH6g&amp;quot; target=&amp;quot;_blank&amp;quot;&amp;gt;Spotify&amp;lt;/a&amp;gt;.&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p class=&amp;quot;text-center&amp;quot;&amp;gt;* * *&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Enterprises face severe disruption, whether via technology, business model, new competition, etc. In order to keep up, organizations must answer fundamental questions about the nature of their business, starting with their people. “What kind of culture do we need to compete in our industry? What does it look like, feel like, sound like? What are the base skills our people possess? Where do they come from?”&amp;amp;nbsp;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;These are some of the questions Reggie Walker, Chief Commercial Officer at PwC, has wrestled with while leading the enterprise&amp;#39;s communications function over the past three years. He’s led a critical organization-wide effort around digital upskilling to better align PwC’s people with its business strategy. He’s also unified the Communications, Sales and Marketing functions, streamlining an operation that was once disparate entities.&amp;amp;nbsp;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;On this episode of The New CCO, we’ll learn more about each of these initiatives from Reggie and how they ladder up to a new kind of CCO role that’s swiftly changing in order to adapt to new disruptive factors.&amp;amp;nbsp;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Here’s Reggie’s take on where he sees the future of work going over the next five years:&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;“The opportunities are almost endless. We have to be responsible. And by that I mean there’s a lot of things we can do with technology. We have to make sure we’re not overextending the reach of certain technologies and cannibalizing jobs and opportunities. But, man, where will it not take us? That’s the fun part.”&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;&amp;lt;em&amp;gt;Do you have a story to tell? Share it with us. Please reach out to Justin Pallenik at &amp;lt;a href=&amp;quot;mailto:jpallenik@page.org&amp;quot; target=&amp;quot;_blank&amp;quot;&amp;gt;jpallenik@page.org&amp;lt;/a&amp;gt; with your CCO story.&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt;</content>
    <author>

1 Ответ

0 голосов
/ 30 апреля 2019

Вы не используете взорвать правильно для того, что вы пытаетесь сделать. Explode

<?php
$thing = "<content type=\"html\">&lt;img alt=\"\" class=\"attachment image image\" src=\"http://awpagesociety.com/attachments/20aa91b841d6a49dd945a97af37509add2680573/store/limit/452/300/e6941ac426f6cbca5774cad6f2e8b6447c96d92d32957be6709dac201de7/Brady-Bush.jpg\"";
var_dump($thing);
$exp = explode("src=", $thing);
var_dump($exp);
?>

[root@test ~]# ./test.php
string(246) "<content type="html">&lt;img alt="" class="attachment image image" src="http://awpagesociety.com/attachments/20aa91b841d6a49dd945a97af37509add2680573/store/limit/452/300/e6941ac426f6cbca5774cad6f2e8b6447c96d92d32957be6709dac201de7/Brady-Bush.jpg""
array(2) {
  [0]=>
  string(67) "<content type="html">&lt;img alt="" class="attachment image image" "
  [1]=>
  string(175) ""http://awpagesociety.com/attachments/20aa91b841d6a49dd945a97af37509add2680573/store/limit/452/300/e6941ac426f6cbca5774cad6f2e8b6447c96d92d32957be6709dac201de7/Brady-Bush.jpg""
}

Дополнительные кавычки являются побочным продуктом, когда они помещаются в строку, например, в целях примера, но при этом вы получите URL-адрес, если он последовательно является последним элементом строки. Если это не так, вы можете взять $ exp [1] и снова взорвать его, используя пробел ("") в качестве стрелки и $ exp [1] в качестве стога сена. Полученный массив будет иметь URL в качестве первого элемента.


Обновление до OP Комментарий / код:

Пожалуйста, прочитайте документацию для взрыва.

$ вещь назначена определенной строке

Explode работает только на струнах. Если я правильно вас интерпретирую, значение xml, которое я поместил в пример строки ...

<content type="html">&lt;img alt="" class="attachment image image" src="http://awpagesociety.com/attachments/20aa91b841d6a49dd945a97af37509add2680573/store/limit/452/300/e6941ac426f6cbca5774cad6f2e8b6447c96d92d32957be6709dac201de7/Brady-Bush.jpg"

- это значение $post['content']. Если это так, то это строка, которую вы хотите взорвать. Часть, которую вы пропустили:

Explode возвращает массив

Чтобы получить один фрагмент взорванной строки, вам нужно сослаться на правильный индекс полученного массива. Посмотрите на мой первоначальный пример еще раз, чтобы точно увидеть, что возвращает Explode:

 array(2) {
  [0]=>
  string(67) "<content type="html">&lt;img alt="" class="attachment image image" "
  [1]=>
  string(175) ""http://awpagesociety.com/attachments/20aa91b841d6a49dd945a97af37509add2680573/store/limit/452/300/e6941ac426f6cbca5774cad6f2e8b6447c96d92d32957be6709dac201de7/Brady-Bush.jpg""
}

Это массив, заполненный строками. Присваивая возврат Explode этому ключу 'post_img', вы делаете значение целым массивом, а не одной строкой. Создание многомерного массива в $ posts, а затем попытка ссылаться на значения, как если бы они были отдельными элементами, это никогда не сработает.

Если это все еще не проясняет ситуацию, предоставьте полный пример XML, возвращаемого simplexml_load_file().

...