値の1つとして以下を含む配列があります
<meta itemprop="datePublished" content="Mon Mar 04 08:52:45 PST 2013"/>
2013年3月4日をそこから抽出するにはどうすればよいですか?これは動的なフィールドであり、常に変化します。私はそれを行う正しい方法を見つけることができないようです
$datepubをエコーできるようにしたい。日付を入力してください。
ありがとう
非常に簡単な方法は、それを爆発させることです:
//dividing the string by whitespaces
$parts = explode(' ', $datepub);
echo $parts[1]; //month (Mar)
echo $parts[2]; //day (04)
echo $parts[5]; //year (2013)
次に、createFromFormat関数を使用して、他の望ましい形式に変換できます。
//creating a valid date format
$newDate = DateTime::createFromFormat('d/M/Y', $parts[1].'/'.$parts[2].'/'.$parts[5]);
//formating the date as we want
$finalDate = $newDate->format('F jS Y'); //March 4th 2013
SimpleXMLを使用したコード例でMarc Bの回答を拡張するには:
$data = '<?xml version="1.0"?><meta itemprop="datePublished" content="Mon Mar 04 08:52:45 PST 2013"/>'; // your XML
$xml = simplexml_load_string($data);
// select all <meta> nodes in the document that have the "content" attribute
$xpath1 = $xml->xpath('//meta[@content]');
foreach ($xpath1 as $key => $node) {
echo $node->attributes()->content; // Mon Mar 04 08:52:45 PST 2013
}
// Marc B's select "content" attribute for all <meta> nodes in the document
$xpath2 = $xml->xpath('//meta/@content');
foreach ($xpath2 as $key => $node) {
echo $node->content; // Mon Mar 04 08:52:45 PST 2013
}