来自< p>的文字标签使用DOM Php [英] Text from <p> tag using DOM Php

查看:134
本文介绍了来自< p>的文字标签使用DOM Php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,
考虑我有以下html语法

Hey, Consider i have the follwing html syntax

<p>xyz</p>
<p>abc</p>

这是我的代码。

<?php
$link='http://www.xyz.com';
$ret= getLinks($link);
print_r ($ret);

function getLinks($link)
{
    /*** return array ***/
    $ret = array();

    /*** a new dom object ***/
    $dom = new domDocument;

    /*** get the HTML (suppress errors) ***/
    @$dom->loadHTML(file_get_contents($link));

    /*** remove silly white space ***/
    $dom->preserveWhiteSpace = false;

    /*** get the links from the HTML ***/
    $text = $dom->getElementsByTagName('p');

/*** loop over the links ***/
    foreach ($text as $tag)
    {
        $ret[] = $tag->innerHTML;
    }

    return $ret;
}
?>

但是我得到一个空的结果。呃,我在这里呀?

But i get an empty result. wat am i miissing here.?

推荐答案

要抑制解析错误,请执行使用

To suppress parsing errors, do not use

@$dom->loadHTML(file_get_contents($link));

libxml_use_internal_errors(TRUE);

此外,没有理由使用 file_get_contents 。 DOM可以从远程资源加载。

Also, there is no reason to use file_get_contents. DOM can load from remote resources.

libxml_use_internal_errors(TRUE);
$dom->loadHTMLFile($link);
libxml_clear_errors();

此外,标记名称区分大小写。当代码段包含< p> 时,您正在查询< P> 。更改为

Also, Tag Names are case sensitive. You are querying for <P> when the snippet contains <p>. Change to

$text = $dom->getElementsByTagName('p');

最后,没有 innerHTML 。用于取得用户的解决方案是在

And finally, there is no innerHTML. A userland solution to fetch it is in

  • How to get innerHTML of DOMNode?

您可以获取 outerHTML

$ret[] = $dom->saveHtml($tag); // requires PHP 5.3.6+

$ret[] = $dom->saveXml($tag); // that will make it XML compliant though

要获取P标签的文本内容,请使用

To get the text content of the P tag, use

$ret[] = $tag->nodeValue;

这篇关于来自&lt; p&gt;的文字标签使用DOM Php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆