没有不值得去解决的问题,也没有不值得去学习的技术!

Find HTML Tags With jQuery-Style Selectors in Yii 2

Searching for "yii2 html dom" on GitHub and ultimately choosing garyjl/yii2-simple_html_dom

1. The HTML data structure is as follows. Now I need to extract: Video description…., which is the data inside the first p tag.

HTML
<!--PLAYERCODESTART-->
<div id="4ce305d265eb4cd7a17db4c4b09ae1d8"></div>
<script type="text/javascript">var vmsPlayer_callback = function () {createPlayer("video://vid:166bc1bf143c445a9e6ad0ce0565b517","%3Fguid%3D166bc1bf143c445a9e6ad0ce0565b517%26siteId%3D2","2018-03-13","@WIDTH@","@HEIGHT@")};</script>
<script type="text/javascript" src="http://wjmserver.chinamcloud.com/vms/site/kfcs/media/playerJson/vod/4ce305d265eb4cd7a17db4c4b09ae1d8.js"></script>
<!--PLAYERCODEEND-->
<div style="font-size:18px;line-height:1.5;" id="editWrap">
    <p>视频描述。。。。</p>
    <p style="text-align: center;">
        <img border="0" style="max-width:100%;" zcmsimagerela="7734" src="http://wjtest.sobeycloud.com/cms/ptu//upload/Image/mrtp/1_6e70e22f7bb447b6a4e75a2979fb4516.jpg?1520927692325" alt="1_640_400"/>
    </p>
    <p>
        <br/>
    </p>
</div>

2. I searched for “yii2 html dom” on GitHub and ultimately chose garyjl/yii2-simple_html_dom, as shown in Figure 1.

Searching for "yii2 html dom" on GitHub and ultimately choosing garyjl/yii2-simple_html_dom
Figure 1

3. I ran the command: composer require –prefer-dist garyjl/yii2-simple_html_dom “*” to install the extension, but the installation failed, as shown in Figure 2.

Running the command: composer require --prefer-dist garyjl/yii2-simple_html_dom "*" to install the extension, but the installation failed
Figure 2

but these conflict with your requirements or minimum-stability.

4. I edited composer.json and added: “garyjl/yii2-simple_html_dom”: “*@dev” to set support for the @dev stability tag, as shown in Figure 3.

JSON

"require": {
    "php": ">=5.6.0",
    "ext-intl": "*",
    "yiisoft/yii2": "^2.0.6",
    "yiisoft/yii2-bootstrap": "^2.0.0",
    "yiisoft/yii2-swiftmailer": "^2.0.0",
    "yiisoft/yii2-authclient": "^2.0.0",
    "yiisoft/yii2-jui": "^2.0.0",
    "asofter/yii2-imperavi-redactor": "dev-master@dev",
    "mihaildev/yii2-elfinder": "^1.0",
    "trntv/yii2-aceeditor": "^2.0",
    "trntv/probe": "^0.2",
    "trntv/yii2-file-kit": "^1.0.0",
    "trntv/yii2-glide": "^1.0.0",
    "trntv/yii2-datetime-widget": "^1.0.0",
    "trntv/cheatsheet": "^0.1@dev",
    "trntv/yii2-command-bus": "^2.0",
    "intervention/image": "^2.1",
    "vlucas/phpdotenv": "^2.0",
    "bower-asset/admin-lte": "^2.0",
    "bower-asset/font-awesome": "^4.0",
    "bower-asset/html5shiv": "^3.0",
    "bower-asset/jquery-slimscroll": "^1.3",
    "bower-asset/flot": "^0.8",
    "symfony/process": "^3.0",
    "yiisoft/yii2-redis": "^2.0",
    "hprose/hprose-yii": "^2.0",
    "garyjl/yii2-simple_html_dom": "*@dev"
  },

Editing composer.json to add: "garyjl/yii2-simple_html_dom": "*@dev", setting support for the @dev stability tag
Figure 3

5. I ran the command: composer update, which executed successfully, as shown in Figure 4.

Running the command: composer update, executed successfully
Figure 4

6. For the content type: video, I extracted the data from the first p tag of $content[‘content’].

PHP

use garyjl\simplehtmldom\SimpleHtmlDom;

$html = SimpleHtmlDom::str_get_html($content['content']);
$content = $html->find('p', 0)->text();
print_r($content);
exit;

7. The printed result matches expectations, as shown in Figure 5.

Plaintext
Video description....

Printed result, matches expectations
Figure 5

8. Upgrading to the production environment, I edited .env to adjust the environment to production.

Plaintext

YII_DEBUG   = false
YII_ENV     = prod

9. I ran the program and encountered an error. I checked: \api\runtime\logs\app.log

Plaintext

2018-03-20 11:04:20 [api][/v1/content-audits?tenantid=default][error][Error] Error: Class 'garyjl\simplehtmldom\SimpleHtmlDom' not found in /sobey/www/cmcp-api/api/models/ContentAudit.php:437
Stack trace:
#0 /sobey/www/cmcp-api/api/rests/content_audit/CreateAction.php(55): api\models\ContentAudit->create()
#1 [internal function]: api\rests\content_audit\CreateAction->run()
#2 /sobey/www/cmcp-api/vendor/yiisoft/yii2/base/Action.php(94): call_user_func_array(Array, Array)
#3 /sobey/www/cmcp-api/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\Action->runWithParams(Array)
#4 /sobey/www/cmcp-api/vendor/yiisoft/yii2/base/Module.php(528): yii\base\Controller->runAction('create', Array)
#5 /sobey/www/cmcp-api/vendor/yiisoft/yii2/web/Application.php(103): yii\base\Module->runAction('v1/content-audi...', Array)
#6 /sobey/www/cmcp-api/vendor/yiisoft/yii2/base/Application.php(386): yii\web\Application->handleRequest(Object(yii\web\Request))
#7 /sobey/www/cmcp-api/api/web/index.php(23): yii\base\Application->run()
#8 {main}
2018-03-20 11:04:20 [api][/v1/content-audits?tenantid=default][warning][yii\log\Dispatcher::dispatch] Unable to send log via yii\log\EmailTarget: Exception 'Swift_TransportException' with message 'Expected response code 220 but got code "", with message ""'

in /sobey/www/cmcp-api/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:419

Stack trace:
#0 /sobey/www/cmcp-api/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(325): Swift_Transport_AbstractSmtpTransport->assertResponseCode('', Array)
#1 /sobey/www/cmcp-api/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(130): Swift_Transport_AbstractSmtpTransport->readGreeting()
#2 /sobey/www/cmcp-api/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php(52): Swift_Transport_AbstractSmtpTransport->start()
#3 /sobey/www/cmcp-api/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(67): Swift_Transport_SendmailTransport->start()
#4 /sobey/www/cmcp-api/vendor/yiisoft/yii2-swiftmailer/Mailer.php(150): Swift_Mailer->send(Object(Swift_Message))
#5 /sobey/www/cmcp-api/vendor/yiisoft/yii2/mail/BaseMailer.php(263): yii\swiftmailer\Mailer->sendMessage(Object(yii\swiftmailer\Message))
#6 /sobey/www/cmcp-api/vendor/yiisoft/yii2/mail/BaseMessage.php(49): yii\mail\BaseMailer->send(Object(yii\swiftmailer\Message))
#7 /sobey/www/cmcp-api/vendor/yiisoft/yii2/log/EmailTarget.php(88): yii\mail\BaseMessage->send(Object(yii\swiftmailer\Mailer))
#8 /sobey/www/cmcp-api/vendor/yiisoft/yii2/log/Target.php(133): yii\log\EmailTarget->export()
#9 /sobey/www/cmcp-api/vendor/yiisoft/yii2/log/Dispatcher.php(189): yii\log\Target->collect(Array, true)
#10 /sobey/www/cmcp-api/vendor/yiisoft/yii2/log/Logger.php(177): yii\log\Dispatcher->dispatch(Array, true)
#11 /sobey/www/cmcp-api/vendor/yiisoft/yii2/base/ErrorHandler.php(113): yii\log\Logger->flush(true)
#12 [internal function]: yii\base\ErrorHandler->handleException(Object(Error))
#13 {main}

10. I checked Git and found that the \vendor\garyjl\yii2-simple_html_dom directory was empty, as shown in Figure 6.

Checking Git and finding that the \vendor\garyjl\yii2-simple_html_dom directory is empty
Figure 6

11. I deleted it and added it to the ignore list: \vendor\garyjl\yii2-simple_html_dom, as shown in Figure 7.

Deleting and adding to the ignore list: \vendor\garyjl\yii2-simple_html_dom
Figure 7

12. I edited .gitignore, deleted the line: /vendor/garyjl/yii2-simple_html_dom, and saved the file, as shown in Figure 8.

Editing .gitignore, deleting the line: /vendor/garyjl/yii2-simple_html_dom, and saving
Figure 8

13. I deleted the directory: \vendor\garyjl\yii2-simple_html_dom\.git, as shown in Figure 9.

Deleting the directory: \vendor\garyjl\yii2-simple_html_dom\.git
Figure 9

14. I added: /vendor/garyjl/yii2-simple_html_dom, as shown in Figure 10.

Adding: /vendor/garyjl/yii2-simple_html_dom
Figure 10

15. I checked \common\config\base.php

PHP

$config = [
    'components' => [
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            //'useFileTransport' => true,
            'messageConfig' => [
                'charset' => 'UTF-8',
                'from' => env('ADMIN_EMAIL')
            ]
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                'file'=>[
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                    'except' => ['yii\web\HttpException:*', 'yii\i18n\I18N\*'],
                    'prefix' => function () {
                        $url = !Yii::$app->request->isConsoleRequest ? Yii::$app->request->getUrl() : null;
                        return sprintf('[%s][%s]', Yii::$app->id, $url);
                    },
                    'logVars'=>[],
                ],
                'httpRequest'=>[
                    'class' => 'yii\log\FileTarget',
                    'logFile' => '@runtime/logs/http-request.log',
                    'categories' => ['yii\httpclient\*'],
                ]
            ],
        ],
    ],
];
if (YII_ENV_PROD) {
    $config['components']['log']['targets']['email'] = [
        'class' => 'yii\log\EmailTarget',
        'except' => ['yii\web\HttpException:*'],
        'levels' => ['error', 'warning'],
        'message' => ['from' => env('ROBOT_EMAIL'), 'to' => env('ADMIN_EMAIL')]
    ];
}

16. I commented out the log target: [[yii\log\EmailTarget|email target]] and edited \common\config\base.php

PHP

/*
if (YII_ENV_PROD) {
    $config['components']['log']['targets']['email'] = [
        'class' => 'yii\log\EmailTarget',
        'except' => ['yii\web\HttpException:*'],
        'levels' => ['error', 'warning'],
        'message' => ['from' => env('ROBOT_EMAIL'), 'to' => env('ADMIN_EMAIL')]
    ];
}
*/

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系