gpt4 book ai didi

php - 使用 DOMDocument 获取值

转载 作者:行者123 更新时间:2023-11-28 01:32:46 25 4
gpt4 key购买 nike

我正在尝试使用 DOMDocument 从以下 html 片段中获取一个值:

<h3>
<meta itemprop="priceCurrency" content="EUR">€

<meta itemprop="price" content="465.0000">465
</h3>

我需要从此代码片段中获取值 465。为此,我使用以下代码:

foreach($dom->getElementsByTagName('h3') as $h) {
foreach($h->getElementsByTagName('meta') as $p) {

if($h->getAttribute('itemprop') == 'price') {
foreach($h->childNodes as $child) {
$name = $child->nodeValue;
echo $name;
$name = preg_replace('/[^0-9\,]/', '', $name);
// $name = number_format($name, 2, ',', ' ');
if (strpos($name,',') == false)
{
$name = $name .",00";
}
}
}
}
}

但是这段代码没有获取值...任何人都可以帮我解决这个问题。

最佳答案

您的 HTML 无效。 meta 的结束标记在哪里?这就是您获得所见结果的原因。

要查找您要查找的内容,您可以使用 xpath:

$doc = new \DOMDocument();
$doc->loadXML($yourHTML);

$xpath = new DOMXpath($doc);
$elements = $xpath->query("//meta[@itemprop='price']");
echo $elements->item(0)->textContent;

关于php - 使用 DOMDocument 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29772619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com