Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

【PHP】simplexml_load_file()のパースエラーが出た時の対処法。XMLが急に表示されなくなった。

こんにちは。

数日ぶりに自分のつくったサイトを見た時に
外部から呼び出しているRSSが表示されなくなっていました。

急にだったので焦りましたが
ローカルでMAMPでみたところ
バリバリのバリエラーが出ていました。

simplexml_load_file()  ~~~~~  parser error

という感じでズラ〜っと表示されていました。

あっさり直ったので
直す方法と参考にしたサイトを書いていきます。

simplexml_load_file() ~~~ parser errorの対処法

パースエラーなので簡単に言えば構文エラーです。

ですが、急になったので戸惑いました。
特に文法もおかしくないし・・・。

原因を探ったところ
simplexml_load_file()でXMLを呼び出した際に
不正な文字列がありました。

ダブルクォート「“」とか。

XMLを修正すればエラーは解除しますが
今後のことを考え、PHPのコードを直しました。

【修正前のコード】

[php]
$xml = “https://hasethblog.com/feed”;
$xmlData = simplexml_load_file($xml);
$json = json_encode($xmlData);
$array = json_decode($json,TRUE);
$news_count = count($array[“channel”][“item”]);
[/php]

ネットでいろんな記事を参考にして書いたコードですが、
シンプルなコードすぎてエラーが発生したようです。

参考にしたサイトは

 

なんとか修正して

【修正後のコード】

[php]
$xml = “https://hasethblog.com/feed”;
$html = file_get_contents($xml);
$invalid_characters = ‘/[^\x9\xa\x20-\xD7FF\xE000-\xFFFD]/’;
$html = preg_replace($invalid_characters, ”, $html);
$xmlData = simplexml_load_string($html);
$json = json_encode($xmlData);
$array = json_decode($json,TRUE);
$news_count = count($array[“channel”][“item”]);
[/php]

このように修正したところ無事表示されるようになりました。

勉強になりました。

コメント

スポンサーリンク
スポンサーリンク
タイトルとURLをコピーしました