2017-11-02 9 views
0

解決策を探してから時間がたっても、問題が見つからないか、問題に合っていません。sitemap.xmlに文字列を追加する方法</urlset>タグを閉じるには、PHPで

基本的に、私は新しいページを作成するダイナミックなウェブサイトを、持っていると私はそれに私が使用している場合sitemap.xmlとに

をその新しいページを追加する機能を追加したい:

file_put_contents("$sitemap_file", $string_to_add, FILE_APPEND); 

/urlsetタグの後にsitemap.xmlの最後に$string_to_addを追加します。

/urlsetタグの前にこの文字列を追加する方法はありますか?現時点では

マイコード:

$date_mod = date('Y-m-d'); 
$string = " 
<url> 
    <loc>https://www.mywebsite.com$internal_link</loc> 
    <lastmod>$date_mod</lastmod> 
    <changefreq>monthly</changefreq> 
</url>"; 

file_put_contents("$root/sitemap.xml", $string, FILE_APPEND); 
+1

はい。 – mega6382

+1

xmlパーサがないと、2つのステップでそれを行う必要があります。 1. 'str_replace'を使用して' 'を削除し、2. $ stringを追加します。 '' '。 – panther

+0

提供されたソリューションのいずれかが役に立った場合は、必ずそれを受け入れてください。 – mega6382

答えて

1

あなたがSimpleXMLを使用して、以下のような何か試すことができます。

$date_mod = date('Y-m-d'); 
$string = " 
<url> 
    <loc>https://www.mywebsite.com$internal_link</loc> 
    <lastmod>$date_mod</lastmod> 
    <changefreq>monthly</changefreq> 
</url>"; 


$xml = simplexml_load_file("$root/sitemap.xml"); 
$xml->addChild($string); 

file_put_contents("$root/sitemap.xml", $xml->asXML()); 

をこれがうまくいけば、<url><urlset>内部タグを配置します。

+0

「<」良い作品が、それは私はそれは問題ではない、とも文字列の間には、余分なを追加したとしている「/&GT」を追加私はちょうど補償するための文字列テキストから削除された: /> \t \t test3に \t \t \t \t 毎月 \t/> \t \t test3に \t \t \t \t 毎月 \t /> –

+0

はい、これは例を与えることだけだった、あなたは[SimpleXMLは](http://php.netへのリンクに従ってください/manual/en/book.simplexml.php)、それについてもっと学びましょう。あなたは間違いなくあなたの要件に少しこのコードをtweekする必要があります。 – mega6382

+0

ty so very much –

0

ただ、SimpleXMLを使用します。代わりに、XMLパーサーを使用することにより、

// You can also do 
// $xmlStr= file_get_contents('sitemap.xml'); 
$xmlStr=<<<XML 
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> 
<url> 
<loc>http://domain.fake/link1.html</loc> 
<priority>1.0</priority> 
</url> 
<url> 
<loc>http://domain.fake/link2.html</loc> 
<priority>0.99</priority> 
</url> 
</urlset> 
XML; 

// Create the SimpleXML object from the string 
$xml = simplexml_load_string($xmlStr); 
// add an <url> child to the <urlset> node 
$url = $xml->addChild("url"); 
// add the <loc> and <priority> children to the <url> node 
$url->addChild("loc", "http://domain.fake/link2.html"); 
$url->addChild("priority", 0.98); 

// get the updated XML string 
$newXMLStr = $xml->asXML(); 
//write it to the sitemap.xml file 
file_put_contents('sitemap.xml',$newXMLStr); 
関連する問題