【问题标题】:Convert html tags to php array将html标签转换为php数组
【发布时间】:2016-05-30 13:19:29
【问题描述】:

我有一个来自合作伙伴的系统状态页面,我正在尝试转换它,以便我可以自动将其输入到我自己的服务页面中。服务的状态由<span> 类提供。我知道这远非理想,但这是他们提供更新的唯一方式。

以下是 HTML 的副本:

<ul class="item-3">
    <li class="status service1">
        <span class="icon"></span>
        <h6>
        SERVICE 1
        </h6>
        <p>
        Updated:
        9:52 AM CST Apr, 24
        </p>
        <span class="arrow up"></span>
    </li>
    <li class="status service2">
        <span class="icon"></span>
        <h6>
        SERVICE 2
        </h6>
        <p>
        Updated:
        9:52 AM CST Apr, 24
        </p>
        <span class="arrow up"></span>
    </li>
    <li class="status service3">
        <span class="icon"></span>
        <h6>
        SERVICE 3
        </h6>
        <p>
        Updated:
        9:52 AM CST Apr, 24
        </p>
        <span class="arrow up"></span>
    </li>
</ul>

我需要获取&lt;span class="arrow up"&gt; 值,因为这是服务状态,&lt;li class="status service3"&gt; 因为这告诉我它是什么服务。

由于我的状态页面 API 使用 ID 而不是“向上/向下”等,因此我需要将状态和服务放在数组中,以便将它们转换为我的格式。

【问题讨论】:

标签: javascript php html dom


【解决方案1】:
$xml = new SimpleXMLElement($html);

$result = $xml->xpath('//ul/li');
$up = array(); //array of servises that is 'up'
$down = array(); //array of servises that is 'down'
foreach ($result as $item)
{
    if (strpos($item->span[1]->attributes()->class, 'up') !== false)
    {
        $up[] = str_replace("status ", "", $item->attributes()->class);
    }

    if (strpos($item->span[1]->attributes()->class, 'down') !== false)
    {
        $down[] = str_replace("status ", "", $item->attributes()->class);
    }
}

var_dump($up);
var_dump($down);

将输出“Up”系统状态

array(3) {
  [0]=>
  string(8) "service1"
  [1]=>
  string(8) "service2"
  [2]=>
  string(8) "service3"
}

【讨论】:

  • 感谢@Dumkaaa,但我如何告诉它从文件中加载 html?
  • @red-spider 简单使用 file_get_contents 从其他网站加载:$html = file_get_contents('http://example.com'); 或从您的网站 include_path // &lt;= PHP 5 $file = file_get_contents('./people.txt', true); // &gt; PHP 5 $file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
  • 感谢@Dumkaaa,这似乎已将其加载,但是我似乎仍然无法使其正常工作。我可以输出整个 SimpleXMLElement,但不能输出上面显示的数组示例。
  • @red-spider var_dump($up) 显示状态为“up”的服务数组
  • 输出NULLPHP Notice: Undefined variable: up
猜你喜欢
  • 1970-01-01
  • 2020-08-17
  • 2013-08-14
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 2023-04-04
  • 2012-03-08
相关资源
最近更新 更多