如何在PHP中使用xhtml:link解析XML?

How to parse an XML with xhtml:link in PHP?

提问人:taketheleap 提问时间:2/16/2019 更新时间:2/20/2019 访问量:1848

问:

目标:

  • 导入外部 XML 文件(在此示例中,它是内联的)
  • 获取< loc >,保存到变量中
  • 找到具有 href-lang=“fr-ca” 属性的< xhtml:link >,获取 href 值,保存到变量中
  • 在数据库中插入两者

我遇到的问题:我什至无法让PHP识别xhtml:link是<url>项的childNode;即使我只是简单地吐出< url >的 nodeValue,它也会省略所有< xhtml:link >子节点。

我正在使用/尝试的代码:

<?php
$xml = <<< XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:xhtml="http://www.w3.org/1999/xhtml">
<url xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <loc>https://www.example.com/ca/en/cat/categories/series/07660/</loc>
  <lastmod>2018-11-07</lastmod>
  <changefreq>daily</changefreq>
  <priority>1.0</priority>
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="en-ae" href="https://www.example.com/ae/en/cat/categories/series/07660/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="de-at" href="https://www.example.com/at/de/cat/07660/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="en-au" href="https://www.example.com/au/en/cat/categories/series/07660/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="en-ca" href="https://www.example.com/ca/en/cat/categories/series/07660/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="fr-ca" href="https://www.example.com/ca/fr/cat/categories/series/07660/" />
</url>
<url xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <loc>https://www.example.com/ca/en/cat/categories/series/07683/</loc>
  <lastmod>2018-11-07</lastmod>
  <changefreq>daily</changefreq>
  <priority>1.0</priority>
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="en-ae" href="https://www.example.com/ae/en/cat/categories/series/07683/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="de-at" href="https://www.example.com/at/de/cat/07683/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="en-au" href="https://www.example.com/au/en/cat/categories/series/07683/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="fr-be" href="https://www.example.com/be/fr/collections/07683/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="nl-be" href="https://www.example.com/be/nl/collecties/07683/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="en-bh" href="https://www.example.com/bh/en/cat/07683/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="en-ca" href="https://www.example.com/ca/en/cat/categories/series/07683/" />
  <xhtml:link xmlns:xhtml="http://www.w3.org/1999/xhtml" rel="alternate" hreflang="fr-ca" href="https://www.example.com/ca/fr/cat/categories/series/07683/" />
</url>
</urlset>
XML;

$urlsxml = new DOMDocument;
$urlsxml->loadXML($xml);
$urls = $urlsxml->getElementsByTagName('url');

for ($i = 0; $i < $urls->length; $i++) {

      echo $urls->item($i)->nodeValue;
      echo $urls->getElementsByTagName("xhtml:link")->attributes->getNamedItem("hreflang")->nodeValue;

      // INSERT INTO DB

}

?>

出主意;任何帮助将不胜感激。

php xml 解析 xhtml hreflang

评论


答:

0赞 Professor Abronsius 2/16/2019 #1

插入数据库的实际行为超出了此处代码的范围,但要解析 XML,您可以做这样简单的事情(基于本地保存的 XML 副本,而不是使用语法)~ 文件名仅用于识别。heredoc

最初,我认为这需要在 XPath 表达式中注册和使用,但事实并非如此 - 对每个节点进行简单的 XPath 查询就足够了~使用父节点作为查询的引用节点。namespaceurlurl

$file='so-stack-xml-namespace.xml';


libxml_use_internal_errors( true );
$dom=new DOMDocument;
$dom->validateOnParse=true;
$dom->recover=true;
$dom->strictErrorChecking=true;
$dom->load( $file );
libxml_clear_errors();

$xp=new DOMXPath( $dom );

$urls=$dom->getElementsByTagName('url');
foreach( $urls as $url ){
    $href=$url->nodeValue;
    $frca=$xp->query('xhtml:link[@hreflang="fr-ca"]',$url)->item(0)->getAttribute('href');
    /* do something with the variables...add to DB */
    printf('href:%s<br />frca:%s<br /><br />', $href,$frca);
}
-1赞 Marco somefox 2/16/2019 #2

如果将 XML 文件放入变量中,则可以使用循环提取值:

$xml = file_get_contents("your_xml_file");
$tags = explode("<", $xml);
$loc = "not found";
$frhref = "not found";

foreach ($tags as $tag){
    if(strpos($tag, "loc>") === 0){
        $loc = substr($tag, 4);
    }
    if(strpos($tag, "xhtml:link") === 0){
        $at = strpos($tag, "hreflang") + 9;
        $lang = substr($tag, $at, 7);
        if($lang == '"fr-ca"'){
            $at = strpos($tag, "href=") + 6;
            $_href = substr($tag, $at);
            $until = strpos($_href, '"');
            $frhref = substr($_href, 0, $until);
        }
    }
}
echo $loc, " ", $frhref; //put them in your db

我用你的内容测试了它:https://3v4l.org/1laON

1赞 ThW 2/20/2019 #3

XML 使用两个不带别名和带别名的命名空间。要读取带有命名空间的 XML,您应该使用 DOM 方法的变体。http://www.sitemaps.org/schemas/sitemap/0.9http://www.w3.org/1999/xhtmlxhtml*NS

$urls = $urlsxml->getElementsByTagNameNS(
  'http://www.sitemaps.org/schemas/sitemap/0.9', 'url'
);

$urls[$i]->getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'link');

第一个参数是命名空间 URI,第二个参数是本地名称(带有前缀的节点名称)。在这种情况下,最好对命名空间 URI 使用常量/变量。

一个更舒适的选择是 Xpath。它允许您使用位置路径和条件来获取节点。

$document = new DOMDocument;
$document->loadXML($xml);
// create an xpath instance for the document
$xpath = new DOMXpath($document);
// register the namespaces for your own prefixes
$xpath->registerNameSpace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$xpath->registerNameSpace('x', 'http://www.w3.org/1999/xhtml');

// iterate all sitemap url elements
foreach ($xpath->evaluate('//s:url') as $url) {
  $data = [
    // get the sitemap loc child element as a string
    'loc' => $xpath->evaluate('string(s:loc)', $url),
    // get the href attribute of the xhtml link element (with language condition)
    'fr-ca' => $xpath->evaluate('string(x:link[@hreflang="fr-ca"]/@href)', $url),
  ];
  var_dump($data);
}

输出:

array(2) { 
  ["loc"]=> 
  string(58) "https://www.example.com/ca/en/cat/categories/series/07660/" 
  ["fr-ca"]=> 
  string(58) "https://www.example.com/ca/fr/cat/categories/series/07660/" 
} 
array(2) { 
  ["loc"]=> 
  string(58) "https://www.example.com/ca/en/cat/categories/series/07683/" 
  ["fr-ca"]=> 
  string(58) "https://www.example.com/ca/fr/cat/categories/series/07683/" 
}

in Xpath 将列表中的第一个节点转换为字符串。它允许您避免对节点对象属性的显式访问。例如,可以写成 .与属性访问不同,如果不存在匹配的节点,则 Xpath 强制转换不会失败并出现错误。它将返回一个空字符串。string()$xpath->evaluate('s:loc', $url)->item(0)->textContent;$xpath->evaluate('string(s:loc)', $url);

评论

0赞 taketheleap 2/21/2019
时代谢谢你。