【发布时间】:2018-08-21 23:33:46
【问题描述】:
首先我寻找了我需要的所有元素,现在我试图从子标题、url 和图像中获取属性值,但总是出错。我究竟做错了什么?
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,
];
}
}
我遇到的错误:
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
【问题讨论】:
-
请添加错误消息并更好地描述您的问题。请避免将 cmets 发布到您自己的问题中,您应该编辑它。请参阅:How to Ask 和 How to write a Minimal, Complete, and Verifiable example。