Converting a DOM element into a string in PHP

拈花ヽ惹草 提交于 2020-01-25 19:57:07

问题


I am running a Wordpress site and using WPML translation plugin. In WPML there is a method called icl_link_to_element(2880); that returns and generates the following element in the DOM:

<a href="https://www.someurl.com/es/atencion-al-cliente">Atención al cliente</a>

I want to convert this element to a string so that I can simply return and store the last part of the url atencion-al-cliente, into a unique variable.

What's the best way to get this done?

Answer to the comment below:

Two elements appear in the DOM now.

<a href="https://www.someurl.com/es/atencion-al-cliente">Atención al cliente</a>

and

"NULL
            "

回答1:


First do the following steps to get that URL

  1. $page = icl_object_id(2880, 'page', true);
  2. $url = get_permalink($page);

Then use $parts = explode("/", $url) function and get the last element of that array, you can use array_pop()




回答2:


Use preg_match to get the value of href, Now get the matched value using parse_url, after getting just collect the path from the return array.

Now its time to get the last portion of the url, So try this below code.

$html = '<a href="https://www.someurl.com/es/atencion-al-cliente">Atención al cliente</a>';

preg_match('/<a href="(.+)">/', $html, $match);

$info = parse_url($match[1]);

$str = $info['path'];
$len = strlen($info['path']);

echo trim(substr($str, strrpos($str, '/'), $len), "/"); //atencion-al-cliente


来源:https://stackoverflow.com/questions/37251703/converting-a-dom-element-into-a-string-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!