提取特定跨度

时间:2018-12-28 15:39:38

标签: php dom domdocument

我正在尝试从网站网址的跨度中提取一个值,但是我无法隔离此特定值...。

这是有问题的跨度

<span data-currency-market="" data-usd="63968175026.0">

我只想要数据使用的值

 $html1 = file_get_contents( 'https://url.com' );
 $dom1 = new DOMDocument();
 @$dom1->loadHTML( $html1 );
 foreach ($dom1->getElementsByTagName('span') as $tag) {
    echo $tag->nodeValue . '<br/>';
 }

2 个答案:

答案 0 :(得分:1)

您可以像这样使用preg_match_all

<?php

    // Loading data for demo
    $html1 = '[...]
    <span data-currency-market="" data-usd="63968175026.0"></span>
    <span data-currency-market="" data-usd="63968175026.0"></span>
    <span data-currency-market="" data-usd="63968175026.0"></span>';

    // Your data source
    //$html1 = file_get_contents( $string );

    preg_match_all('/usd="(.*)"/', $html1, $output_array);

    // Showing array
    echo "<pre>";
    print_r($output_array);
    echo "</pre>";
?>

将输出以下内容:

enter image description here

如果您只需要使用数字

print_r($output_array[1]);

enter image description here

所以最后,您只需要两行代码

$html1 = file_get_contents( $string );
preg_match_all('/usd="(.*)"/', $html1, $output_array);

您可以使用

foreach($output_array[1] as $key=>$value){
    echo $value;
}

获取值

如果您只希望该页面中有一个匹配项,则可以像这样使用preg_match_all代替preg_match_all

<?php
    $html1 = '[...]
    <span data-currency-market="" data-usd="63968175026.0"></span>
    <span data-currency-market="" data-cad="73175026.0"></span>
    <span data-currency-market="" data-eur="83968176.0"></span>';
    //$html1 = file_get_contents( $string );
    preg_match('/usd="(.*)"/', $html1, $output_array);

    echo $output_array[1];
?>

输出:63968175026.0

答案 1 :(得分:0)

要使用DOM正确执行此操作,可以使用XPath查找具有data-usd属性的所有span元素。 XPath只是//span/@data-usd,其中@表示属性。对query()的调用将返回匹配节点的列表,因此您只需循环使用与getElementsByTagName()相同的方式即可。

$html1 = '<div><span data-currency-market="" data-usd="1">
<span data-currency-market="" data-eur="2">
<span data-currency-market="" data-usd="3">
<span data-currency-market="" data-eur="4"></div>';

//$html1 = file_get_contents( 'https://url.com' );
$dom1 = new DOMDocument();
$dom1->loadHTML( $html1 );
$xp = new DOMXPath($dom1);
$dataUSD = $xp->query("//span/@data-usd");
foreach ($dataUSD as $tag) {
    echo $tag->nodeValue . '<br/>';
}

其中包含测试数据的返回值...

1<br/>3<br/>