如何从XPath php中的子级(HTML)获取属性值?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (245)

首先,我寻找了我需要的所有元素,现在我想从子标题,网址和图像中获取属性值。但是一直都是错误。请帮忙,我做错了什么?

function getContent($value)
    {
        $homepage = file_get_contents('https://www.youtube.com/results?search_query=' . $value);

        $doc = new DOMDocument();
        libxml_use_internal_errors(TRUE); //disable libxml errors

        //check if any html is actually returned
        if (!empty($homepage)) {

            //load
            $doc->loadHTML($homepage);

            //remove errors for yucky HTML
            libxml_clear_errors();

            //get DOMxPath
            $scriptXpath = new DOMXPath($doc);

            //get all the <li> elements
            $scriptRows = $scriptXpath->query('//*[@class="item-section"]/li[position()>1]');

            $videos = array();
            foreach ($scriptRows as $scriptRow) {

                $VideoTitle = $scriptRow->{'/div/div/div/h3/a/@title'};
                $VideoUrl = 'https://youtube.com' .$scriptRow->{'/div/div/div[2]/h3/a/@href'};
                $VideoImg =  $scriptRow->{'/div/div/div[1]/a/div/span/img/@src'};
              // add to the end of a array of videos
                $videos[] = [
                    'title' => $VideoTitle,
                    'url' => $VideoUrl,
                    'image' => $VideoImg,
                ];
            }
        }

ERRORS i am getting :

Notice: Undefined property: DOMElement::$/div/div/div/h3/a/@title Notice: Undefined property: DOMElement::$/div/div/div[2]/h3/a/@href Notice: Undefined property:DOMElement::$/div/div/div[1]/a/div/span/img/@src

提问于
用户回答回答于

通过使用getAttribute()解决

 $scriptRows = $scriptXpath->query('//*[@class="item-section"]/li[position()>1]/div/div/div/h3/a');

foreach ($scriptRows as $scriptRow) {

                $VideoTitle = $scriptRow->getAttribute("title");
                $VideoUrl = 'https://youtube.com' .$scriptRow->getAttribute("href");
                $videos[] = [
                    'title' => $VideoTitle,
                    'url' => $VideoUrl,
                    //'image' => $VideoImg,
                ];


            }
                        
 $scriptRows = $scriptXpath->query('//*[@class="item-section"]/li[position()>1]/div/div/div[1]/a/div/span/img');

          

  foreach ($scriptRows as $scriptRow) {
  // add to the end of a array of videos
    $VideoImg =  $scriptRow->getAttribute("src");
    $videos[] = [
      'image' => $VideoImg,
     ];
}

扫码关注云+社区

领取腾讯云代金券